IO and NIO
How data enters and leaves a program
A program rarely lives only in RAM. It reads configuration, saves files,
accepts bytes from external sources, and writes results back.
Java provides two closely related API families for this: classic streams from java.io
and more modern tools from java.nio and java.nio.file.
In this section, we will not try to memorize dozens of class names. It is much more important to understand several models: a file path, a byte stream, a character stream, a buffer, a channel, and a resource that must be closed correctly. Once these ideas are clear, most IO code becomes predictable.
What this section covers
- File and Path. We will see how to represent a path to a file or directory and why modern code is usually built around
Path. - Byte Streams. We will learn to read and write raw bytes through
InputStreamandOutputStream. - Character Streams. We will move from bytes to text and see the role of
Reader,Writer, and character encodings. - Buffered Input and Output. We will see why a buffer is often placed between a program and a data source.
- The Files Class. We will collect the main file and directory operations in a high-level API.
- Channels and Buffers. We will get acquainted with the NIO model, where data moves between a channel and an explicit buffer.
- Serialization. We will examine Java's built-in mechanism for turning objects into a byte stream and back, along with its limitations.
- Resources and try-with-resources. We will connect everything together and reinforce safe management of files, streams, and other closeable resources.
The topics move from representing where data is located to the ways it can be read and written. First, we will learn to choose the right level of abstraction, then work with higher-level operations, and finally deal with resource lifecycle management.
Path path = Path.of("data", "message.txt");
String text = Files.readString(path);
These two lines look simple, but they already involve a path, a file system, reading data, and releasing system resources. Next, we will examine these pieces separately.