Chapter 11. 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 emphasized portability over functionality. As a result, these systems have undergone multiple significant revisions over the platform’s history.
In this chapter we will introduce modern, recommended approaches to file I/O. After that, we’ll touch on the “classic” APIs that you still may encounter in some code. Finally, we’ll cover network communication.
Path
When working with files, you have to know the location of the file you want to
access. The Path interface in the java.nio.file package can be thought of as
representing this file location whether it exists or not. A path is:
-
System dependent
-
Hierarchical
-
Composed of a sequence of path elements
-
Hypothetical (may not exist yet or may have been deleted)
Path is an interface, which enables different filesystem providers to each
implement system-specific features while retaining the overall abstraction. As
opposed to the legacy File class we’ll see later, Path has no notion of the
contents of a file and purely represents a file’s location within the filesystem
(which itself may be abstracted or virtualized).
Note
What’s that NIO in the package name? As mentioned in the introduction, File I/O has seen several large revisions across Java’s history. NIO stands for “New I/O.” Java 7 in particular brought in a brand-new I/O API—usually ...
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