Streams

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

ClassPurposeDirection
InputStreamBase class for byte inputInput
FileInputStreamReads bytes from a fileInput
BufferedInputStreamImproves performance by bufferingInput
OutputStreamBase class for byte outputOutput
FileOutputStreamWrites bytes to a fileOutput
BufferedOutputStreamBuffers writes for efficiencyOutput

3. Main Character Stream Classes

ClassPurposeDirection
ReaderBase class for char inputInput
FileReaderReads characters from a fileInput
BufferedReaderReads text efficiently, supports readLine()Input
WriterBase class for char outputOutput
FileWriterWrites characters to a fileOutput
BufferedWriterBuffers writes, improves performanceOutput
PrintWriterPrints text convenientlyOutput

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 a FileReader).

Leave a Reply