A stream is a sequence of data. I/O streams refers to input output stream - basically reading from a source and writing to a destination.
When to use Character Stream over Byte Stream?
In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files. These text files can be processed character by character. Character size is typically 16 bits = 2byte.
When to use Byte Stream over Character Stream?
Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files.
Key points about working with streams:
Character Stream
In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the destination.
package com.xyz;
import java.io.FileReader;
import java.io.IOException;
//Java Program illustrate Reading
//a File in Human Readable
//Format Using FileReader Class
public class CharacterStreamDemo {
// Main driver method
public static void main(String[] args) throws IOException {
// Initially assigning null as we have not read
// anything
FileReader sourceStream = null;
// Try block to check for exceptions
try {
// Reading from file
sourceStream = new FileReader(
"C:\\\\Users\\\\Windows\\\\Documents\\\\demo.rtf");
// Reading sourcefile and writing content to
// target file character by character.
int temp;
// If there is content inside file
// than read
while ((temp = sourceStream.read()) != -1)
System.out.print((char)temp);
// Display message for successful execution of
// program
System.out.print(
"Program successfully executed");
}
catch (Exception e) {
e.printStackTrace();
}
// finally block that executes for sure
// where we are closing file connections
// to avoid memory leakage
finally {
// Closing stream as no longer in use
if (sourceStream != null)
sourceStream.close();
}
}
}
Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the source and FileOutputStream to write to the destination.