Java I/O stream
🔹 1. What is Java I/O?
I/O stands for Input and Output, and in Java it refers to how your program reads from or writes to:
- Keyboard (System.in)
- Console (System.out)
- Files (FileInputStream/FileWriter)
- Network sockets
- External devices
🔹 2. Stream: The Core of Java I/O
🔸 What is a Stream?
A stream is a continuous flow of data.
In Java, streams abstract away the source or destination of data, and provide a simple way to process it byte by byte or character by character.
🔸 Two Main Stream Types
Type Description Examples
Byte Stream | For binary data (images, audio) | InputStream, OutputStream |
Character Stream | For text (String, text files) | Reader, Writer |
🔹 3. Basic Java Stream Classes
📈 InputStream & OutputStream (Byte Stream)
📌 InputStream
- Abstract class
- Reads 1 byte at a time
Key methods:
int read();
int read(byte[] b);
void close();
Subclasses:
Class Description
FileInputStream | Reads bytes from a file |
BufferedInputStream | Adds buffer for performance |
ByteArrayInputStream | Reads from byte array in memory |
ObjectInputStream | Reads serialized objects |
📌 OutputStream
- Abstract class
- Writes 1 byte at a time
Key methods:
void write(int b);
void write(byte[] b);
void flush();
void close();
Subclasses:
Class Description
FileOutputStream | Writes bytes to a file |
BufferedOutputStream | Adds buffer for performance |
ByteArrayOutputStream | Writes to memory (byte array) |
ObjectOutputStream | Writes serialized objects |
📈 Reader & Writer (Character Stream)
📌 Reader
- Abstract class
- Reads characters (2 bytes, UTF-16)
Key methods:
int read();
int read(char[] cbuf);
void close();
Subclasses:
Class Description
FileReader | Reads characters from a file |
BufferedReader | Adds buffer; supports readLine() |
InputStreamReader | Converts bytes to characters (with encoding) |
📌 Writer
- Abstract class
- Writes characters
Key methods:
void write(int c);
void write(String str);
void write(char[] cbuf);
void flush();
void close();
Subclasses:
Class Description
FileWriter | Writes characters to a file |
BufferedWriter | Adds buffer for performance |
OutputStreamWriter | Converts characters to bytes (with encoding) |
📌 Stream Chaining (Connecting Streams)
Streams can be connected together in layers. This is called Stream Chaining.
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("data.txt"), StandardCharsets.UTF_8));
This pipeline goes: file → byte → character → buffer.
📄 Can InputStreamReader Be Used Alone?
No — InputStreamReader requires an existing InputStream as its source. You must provide it in the constructor. It cannot be used alone.
✅ Correct usage:
InputStreamReader reader = new InputStreamReader(System.in);
int ch = reader.read();
System.out.println((char) ch);
reader.close();
❌ Incorrect (won't compile):
InputStreamReader reader = new InputStreamReader(); // ❌ No default constructor
Always pass an InputStream, such as System.in, FileInputStream, or ByteArrayInputStream, when using InputStreamReader.
🔹 4. File I/O in Java
🔸 Writing Text to File
FileWriter writer = new FileWriter("hello.txt");
writer.write("Hello, world!");
writer.close();
🔸 Reading Text from File
FileReader reader = new FileReader("hello.txt");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
🔸 Writing Binary File
FileOutputStream out = new FileOutputStream("image.png");
out.write(byteData);
out.close();
🔹 5. Buffering for Performance
Reading or writing data one byte/character at a time is inefficient.
Buffered streams improve performance by reducing the number of actual I/O operations.
🔸 BufferedReader Example
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
🔸 BufferedWriter Example
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("This is fast and efficient!");
writer.newLine();
writer.write("Another line.");
writer.close();
🔹 6. Handling Encoding Correctly
Use encoding explicitly when working with international text.
🔸 Writing with UTF-8
Writer writer = new OutputStreamWriter(new FileOutputStream("utf8.txt"), StandardCharsets.UTF_8);
writer.write("안녕하세요");
writer.close();
🔸 Reading with UTF-8
Reader reader = new InputStreamReader(new FileInputStream("utf8.txt"), StandardCharsets.UTF_8);
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
🔹 7. File Copy Example (Buffered)
try (
BufferedInputStream in = new BufferedInputStream(new FileInputStream("source.jpg"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("target.jpg"))
) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
}
🔹 8. Best Practices
- ✅ Always close streams (use try-with-resources)
- ✅ Use Buffered streams for performance
- ✅ Choose Writer/Reader for text, Stream for binary
- ✅ Handle encoding explicitly
- ✅ Match encoding when writing and reading text
🔹 9. Summary Table
Text file write | FileWriter, BufferedWriter |
Text file read | FileReader, BufferedReader |
Binary file copy | BufferedInputStream/OutputStream |
Encoding-safe writing | OutputStreamWriter with charset |
Encoding-safe reading | InputStreamReader with charset |