Great question, Stanley! 🧠 Let’s explore the subclasses of InputStream
and understand what each is used for.
InputStream
is the abstract base class for reading raw bytes in Java.
✅ Common Subclasses of InputStream
Subclass | Purpose |
---|---|
FileInputStream | Reads bytes from a file |
ByteArrayInputStream | Reads bytes from a byte array in memory |
BufferedInputStream | Adds a buffer to another input stream for better performance |
DataInputStream | Reads primitive types (int, double, etc.) in a portable way |
ObjectInputStream | Deserializes Java objects previously written with ObjectOutputStream |
PipedInputStream | Used for inter-thread communication (connected to PipedOutputStream ) |
SequenceInputStream | Combines multiple streams into one continuous stream |
FilterInputStream | Abstract decorator for filtering input (base for other filters) |
PushbackInputStream | Allows pushing bytes back into the stream (for parsers) |
🔍 Explanation with Use Cases
🔹 FileInputStream
Reads raw bytes from a file (e.g. reading an image or binary data).
InputStream in = new FileInputStream("data.bin");
🔹 ByteArrayInputStream
Simulates an input stream from a byte array — no actual file or network involved.
byte[] data = {1, 2, 3};
InputStream in = new ByteArrayInputStream(data);
🔹 DataInputStream
Reads Java primitive data types like int
, double
, boolean
in a portable way.
DataInputStream in = new DataInputStream(new FileInputStream("data.bin"));
int age = in.readInt();
🔹 ObjectInputStream
Reads (deserializes) objects written with ObjectOutputStream
.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.dat"));
MyClass obj = (MyClass) in.readObject();
🔹 PipedInputStream
Used for communication between threads.
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
🔹 SequenceInputStream
Concatenates multiple input streams into one.
SequenceInputStream in = new SequenceInputStream(in1, in2);
🔹 PushbackInputStream
Supports unreading (pushing back) bytes into the stream — useful for custom parsers.
PushbackInputStream in = new PushbackInputStream(new FileInputStream("input.txt"));
🧠 Summary Table
Subclass | Reads From | Special Feature |
---|---|---|
FileInputStream | File | Raw binary file access |
ByteArrayInputStream | Byte array | In-memory data stream |
BufferedInputStream | Any stream | Adds buffering |
DataInputStream | Any stream | Reads Java primitives |
ObjectInputStream | Any stream | Reads objects (serialization) |
PipedInputStream | Another thread | Inter-thread pipe input |
SequenceInputStream | Multiple streams | Concatenates input |
PushbackInputStream | Any stream | Allows “unread” of bytes |