In Java, I/O Streams are the core mechanism for reading from and writing to data sources such as files, network sockets, memory, or even the console.
The term “stream” means a flow of data — either input (reading) or output (writing).
1. Types of Streams
Java classifies streams along two main axes:
a. Direction
- Input Stream → reads data into the program.
- Output Stream → writes data out from the program.
b. Data Type
- Byte Streams (
InputStream
/OutputStream
)- For binary data: images, audio, serialized objects.
- Reads/writes data in 8-bit bytes.
- Character Streams (
Reader
/Writer
)- For text data (Unicode characters).
- Reads/writes data in 16-bit chars.
2. Main Byte Stream Classes
Class | Purpose | Direction |
---|---|---|
InputStream | Base class for byte input | Input |
FileInputStream | Reads bytes from a file | Input |
BufferedInputStream | Improves performance by buffering | Input |
OutputStream | Base class for byte output | Output |
FileOutputStream | Writes bytes to a file | Output |
BufferedOutputStream | Buffers writes for efficiency | Output |
3. Main Character Stream Classes
Class | Purpose | Direction |
---|---|---|
Reader | Base class for char input | Input |
FileReader | Reads characters from a file | Input |
BufferedReader | Reads text efficiently, supports readLine() | Input |
Writer | Base class for char output | Output |
FileWriter | Writes characters to a file | Output |
BufferedWriter | Buffers writes, improves performance | Output |
PrintWriter | Prints text conveniently | Output |
4. Basic Example – File Copy (Byte Stream)
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try (
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt");
) {
int byteData;
while ((byteData = in.read()) != -1) {
out.write(byteData);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Basic Example – Reading Text (Character Stream)
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. Key Points to Remember
- Byte streams: good for binary data.
- Character streams: good for text.
- Use buffered streams for better performance.
- Always close streams (or use try-with-resources to auto-close).
- Many streams can be chained (e.g.,
BufferedReader
wrapping aFileReader
).