Introduction to Java I/O
The java.io package contains nearly all the classes you might need in Java to perform input and output (I/O) operations. These classes enable your Java programs to read data from a source (such as a file, memory, or network socket) and write data to a destination.
In Java, I/O is built around the concept of Streams. A stream represents a continuous flow of data between a program and a source/destination.
The Concept of Streams
A Stream is an abstraction that represents a sequence of data.
- Input Stream: Used to read data from a source.
- Output Stream: Used to write data to a destination.
Byte Streams vs. Character Streams
The java.io package divides streams into two main categories based on the type of data they handle: Byte Streams and Character Streams.
| Feature | Byte Streams | Character Streams |
|---|---|---|
| Data Unit | 8-bit byte (byte) | 16-bit Unicode character (char) |
| Primary Use | Binary data (images, audio, video, zip files, etc.) | Text data (plain text, JSON, XML, etc.) |
| Base Abstract Classes | InputStream and OutputStream | Reader and Writer |
| Encoding | No character encoding. Reads/writes raw bytes. | Handles character encoding (e.g., UTF-8, UTF-16) automatically. |
| Standard Subclasses | FileInputStream, FileOutputStream | FileReader, FileWriter |
[!TIP] Use character streams for reading/writing text files to avoid character corruption (mojibake) due to encoding mismatches. For binary files like images, always use byte streams.
The Stream Hierarchy
Understanding the hierarchy of the java.io package is key to choosing the right tool for the job.
1. Byte Stream Hierarchy
Byte streams are rooted in InputStream and OutputStream. Here are the most commonly used subclasses:
2. Character Stream Hierarchy
Character streams are rooted in Reader and Writer. Here are the main subclasses:
Standard Streams
Java provides three standard streams that are initialized automatically when a program starts. They are static members of the System class:
System.in: Standard input stream, typically connected to keyboard input. It is an instance ofInputStream.System.out: Standard output stream, typically connected to the console. It is an instance ofPrintStream.System.err: Standard error stream, used to output error messages. It is also an instance ofPrintStream.
Let's begin exploring the Java I/O API by learning how to interact with the file system using the File class in the next section!