UNIT 4
STREAM CLASSES
10. STREAM CLASSES
In Java, Stream classes are used to perform input and output (I/O) operations such as reading and writing
data. These are part of the java.io package and work in a stream-oriented manner — meaning data is read
or written sequentially, one piece at a time. Stream classes are broadly categorized into two types:
• Byte Stream Classes – For handling raw binary data.
• Character Stream Classes – For handling text data (character-based).
• Common Subclasses:
• FileInputStream – Reads bytes from a file.
• FileOutputStream – Writes bytes to a file.
• BufferedInputStream – Adds buffering to input for performance.
• BufferedOutputStream – Buffers output before writing to disk.
• DataInputStream / DataOutputStream – Allows reading/writing of Java primitive types (int,
float, etc.).
Example:
FileInputStream in = new FileInputStream("image.jpg");
FileOutputStream out = new FileOutputStream("copy.jpg");
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
in.close();
out.close();
• CHARACTER STREAM CLASSES
• Character streams are used to read and write text (Unicode characters). They automatically handle
character encoding and decoding.
• Key Classes:
• Reader (abstract) – Base class for reading characters.
• Writer (abstract) – Base class for writing characters.
• Common Subclasses:
• FileReader / FileWriter – Reads/writes character files.
• BufferedReader / BufferedWriter – Buffered text input/output.
• PrintWriter – Writes formatted text to files or console.
Example:
FileReader fr = new FileReader("notes.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
USING STREAM WITH FILE CLASS:
The File class in java.io represents a file or directory path, but does not itself perform I/O.
However, it is used to create input/output stream objects.
Example:
File file = new File("data.txt");
FileInputStream fis = new FileInputStream(file);
• OTHER STREAM CLASSES
• 1. ObjectInputStream / ObjectOutputStream
• Used to read/write Java objects (serialization).
• ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("object.dat"));
• oos.writeObject(new Student("John", 101));
• 2. PipedInputStream / PipedOutputStream
• Used for communication between threads via byte streams.
• 3. SequenceInputStream
• Reads data from multiple input streams sequentially as if from one stream.
Thank You