Java.Streams.What subclasses of the InputStream class do you know, what are they for?

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

SubclassPurpose
FileInputStreamReads bytes from a file
ByteArrayInputStreamReads bytes from a byte array in memory
BufferedInputStreamAdds a buffer to another input stream for better performance
DataInputStreamReads primitive types (int, double, etc.) in a portable way
ObjectInputStreamDeserializes Java objects previously written with ObjectOutputStream
PipedInputStreamUsed for inter-thread communication (connected to PipedOutputStream)
SequenceInputStreamCombines multiple streams into one continuous stream
FilterInputStreamAbstract decorator for filtering input (base for other filters)
PushbackInputStreamAllows 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

SubclassReads FromSpecial Feature
FileInputStreamFileRaw binary file access
ByteArrayInputStreamByte arrayIn-memory data stream
BufferedInputStreamAny streamAdds buffering
DataInputStreamAny streamReads Java primitives
ObjectInputStreamAny streamReads objects (serialization)
PipedInputStreamAnother threadInter-thread pipe input
SequenceInputStreamMultiple streamsConcatenates input
PushbackInputStreamAny streamAllows “unread” of bytes
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.