Chapter 10. File Handling and I/O
Java has had input/output (I/O) support since the very first version. However, due to Java’s strong desire for platform independence, the earlier versions of I/O functionality emphasized portability over functionality. As a result, they were not always easy to work with.
We’ll see later in the chapter how the original APIs have been supplemented—they are now rich, fully featured, and very easy to develop with. Let’s kick off the chapter by looking at the original, “classic” approach to Java I/O, which the more modern approaches layer on top of.
Classic Java I/O
The File class is the cornerstone of Java’s original way to do
file I/O. This abstraction can represent both files and directories, but
in doing so is sometimes a bit cumbersome to deal with, and leads to
code like this:
// Get a file object to represent the user's home directoryFilehomedir=newFile(System.getProperty("user.home"));// Create an object to represent a config file (should// already be present in the home directory)Filef=newFile(homedir,"app.conf");// Check the file exists, really is a file, and is readableif(f.exists()&&f.isFile()&&f.canRead()){// Create a file object for a new configuration directoryFileconfigdir=newFile(f,".configdir");// And create itconfigdir.mkdir();// Finally, move the config file to its new homef.renameTo(newFile(configdir,".config"));}
This shows some of the flexibility possible with the File class, but also demonstrates ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access