Java Reference
In-Depth Information
legacy file input and output
Prior to the Java 7 release, the java.io.File class was the default mechanism used for file I/O. This
class is still present for reasons of backward-compatibility, but has several drawbacks:
Some methods don't throw exceptions when an error occurs, or do not provide enough infor-
mation to know the root cause behind a failure.
Well-defined support for links is lacking.
Accessing file metadata can be difficult and slow.
Fetching information over a network introduces scalability issues.
Some methods do not work consistently on various operating systems and platforms.
That being said, a great deal of real-life code still uses the legacy file input and output, so we discuss
it here in brief. Creating a file object is simple:
File myFile = new File("groceries.txt");
Whenever you can, a good way to deal with methods returning legacy File objects is to imme-
diately convert them to a Path using the myFile.toPath() method. Similarly, the Path interface
defines a toFile() method you can use to get a legacy File object from a Path object.
Operations you wish to execute on a File object (such as checking for existence) are not done
through a helper class like Files did on Path objects, but directly on the File object itself, for
example by calling one of its methods. The following list shows the corresponding File methods for
most of the Files equivalents we've discussed:
Path.getFileName(...) was File.getName()
Files.isDirectory(...) was File.isDirectory(...)
Files.isRegularFile(...) was File.isFile(...)
Files.size(...) was File.length(...)
Files.move(...) was File.renameTo(...)
Files.delete(...) was File.delete(...)
Files.createFile(...) was File.createNewFile(...)
Files.createTempFile(...) was File.createTempFile(...)
File.deleteOnExit(...) is now handled by passing DELETE_ON_CLOSE as an option to
Files.createFile(...)
Files.exists(...) and Files.notExists(...) was File.exists(...)
Path.newDirectoryStream(...) was File.list(...) and File.listFiles(...)
Path.createDirectory(...) was File.mkdir(...)
 
Search WWH ::




Custom Search