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 directory
File
homedir
=
new
File
(
System
.
getProperty
(
"user.home"
));
// Create an object to represent a config file (should
// already be present in the home directory)
File
f
=
new
File
(
homedir
,
"app.conf"
);
// Check the file exists, really is a file & is readable
if
(
f
.
exists
()
&&
f
.
isFile
()
&&
f
.
canRead
())
{
// Create a file object for a new configuration directory
File
configdir
=
new
File
(
f
,
".configdir"
);
// And create it
configdir
.
mkdir
();
// Finally, move the config file to its new home
f
.
renameTo
(
new
File
(
configdir
,
".config"
));
}
This shows some of the flexibility possible with the File
class, but also demonstrates ...
Get Java in a Nutshell, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.