Java I/O Stream Fundamentals
To effectively utilize I/O streams in Java, its recommended to first understand the classification hierarchy and then explore the specific usage of individual stream classes.
Overview
- Input: Reads data from a source (disk or network) into the program's memory.
- Output: Writes data from memory out to a destination (disk or network).
Classification of Streams
- Byte Input Stream (
InputStream): Reads raw byte data from a source into memory. - Byte Output Stream (
OutputStream): Writes raw byte data from memory to a destination. - Character Input Stream (
Reader): Reads character data (handling encoding) from a source into memory. - Character Output Stream (
Writer): Writes character data from memory to a destination.
Byte Streams
Reading Bytes with FileInputStream
The FileInputStream reads raw bytes from a file. Note that reading text byte-by-byte may cause encoding issues (e.g., Chinese characters appearing as garbled text).
Constructors:
FileInputStream(String path)FileInputStream(File fileObj)
Reading Methods:
int read(): Reads a single byte. Returns-1at the end of the file.int read(byte[] buffer): Reads bytes into an array. Returns-1at the end.
Example: Reading a single byte:
FileInputStream fis = new FileInputStream("module/data.txt");
int byteVal;
while ((byteVal = fis.read()) != -1) {
System.out.print((char) byteVal);
}
fis.close();
Example: Reading using a buffer array:
FileInputStream fis = new FileInputStream("module/data.txt");
byte[] chunk = new byte[10];
int bytesRead;
while ((bytesRead = fis.read(chunk)) != -1) {
String content = new String(chunk, 0, bytesRead);
System.out.print(content);
}
fis.close();
Example: Loading all bytes:
While you can define a massive array matching the file size, or use readAllBytes(), these approaches are risky for large files as they may cause OutOfMemoryError.
FileInputStream fis = new FileInputStream("module/data.txt");
// Option 1: Manual allocation
// byte[] data = new byte[(int) new File("module/data.txt").length()];
// fis.read(data);
// Option 2: Built-in method
byte[] data = fis.readAllBytes();
System.out.println(new String(data));
fis.close();
Writing Bytes with FileOutputStream
This class writes raw bytes to a file.
Constructors:
FileOutputStream(String path, boolean append): Ifappendis true, data is added to the end of the file.
Writing Methods:
write(int b)write(byte[] b)write(byte[] b, int off, int len)
Example:
FileOutputStream fos = new FileOutputStream("module/output.txt", true);
// Write bytes from a string
String message = "Hello Stream\r\n";
fos.write(message.getBytes());
// Write specific bytes
byte[] nums = {65, 66, 67}; // A, B, C
fos.write(nums, 0, 2);
fos.close();
Character Streams
Reading Characters with FileReader
FileReader is suitable for reading text files as it handles character decoding.
Methods:
int read(): Reads a single character.int read(char[] cbuf): Reads characters into an array.
Example: Reading characters:
FileReader fr = new FileReader("module/poem.txt");
char[] charBuffer = new char[8];
int count;
while ((count = fr.read(charBuffer)) != -1) {
System.out.print(new String(charBuffer, 0, count));
}
fr.close();
Writing Characters with FileWriter
Character streams often require a flush() to ensure data is physically written to the disk before closing.
Methods:
write(int c)write(String str)write(char[] cbuf)
Example:
FileWriter fw = new FileWriter("module/log.txt");
fw.write(98); // char 'b'
fw.write("Sample Text");
char[] chars = {'J', 'a', 'v', 'a' };
fw.write(chars);
// Flush to ensure data is written
fw.flush();
// Close stream (automatically flushes)
fw.close();
Buffered Streams
Buffered streams wrap standard streams to improve performance by reducing physical read/write operations using an internal buffer (default 8192 bytes/chars).
Byte Buffered Streams
BufferedInputStreamBufferedOutputStream
Example:
FileInputStream fis = new FileInputStream("module/largefile.bin");
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] temp = new byte[100];
int len;
while ((len = bis.read(temp)) != -1) {
// Process bytes
}
bis.close();
Character Bufffered Streams
BufferedReader: OffersreadLine()method to read text line by line.
Example:
FileReader fr = new FileReader("module/input.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();