Skip to content
C

InputStream and OutputStream

InputStream and OutputStream are base classes used for reading and writing raw binary data (bytes), such as images, audio files, or any non-text data.


1. What are InputStream and OutputStream?

InputStream and OutputStream are base classes used for reading and writing raw binary data (bytes), such as images, audio files, or any non-text data.

2. Why is it used?

Not all data is plain text — files like images or videos are stored as raw bytes. InputStream and OutputStream (and their subclasses) provide the tools needed to read and write this kind of binary data correctly.

3. Real-Life Example

Think of a water pipe carrying water into a tank (InputStream, bringing data in) and another pipe carrying water out to a different location (OutputStream, sending data out). Data flows through these "pipes" one byte at a time.

4. Syntax

java
InputStream in = new FileInputStream("file.dat"); OutputStream out = new FileOutputStream("output.dat");

5. Example Program

java
import java.io.*; public class StreamDemo { public static void main(String[] args) throws IOException { FileOutputStream out = new FileOutputStream("data.bin"); out.write(65); // writes byte for letter 'A' out.close(); FileInputStream in = new FileInputStream("data.bin"); int data = in.read(); System.out.println("Byte read: " + data); in.close(); } }

Output:

Byte read: 65

6. Key Points to Remember

  • InputStream/OutputStream work with raw bytes, suitable for any type of file, including non-text files.
  • Always close streams after use (or use try-with-resources) to release system resources properly.
  • For plain text specifically, Reader/Writer classes (next topic) are usually a better, more convenient choice.