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

OutputStream is an abstract class in java.io that represents an output stream of bytes — i.e., it lets you write raw binary data to some destination.


🔽 Common Subclasses of OutputStream

SubclassDescription
FileOutputStreamWrites bytes to a file.
BufferedOutputStreamAdds buffering to another output stream to reduce the number of I/O operations.
DataOutputStreamWrites Java primitives (like int, double, etc.) in a machine-independent way.
ByteArrayOutputStreamWrites to an in-memory byte array (can later be converted to a byte[]).
ObjectOutputStreamWrites serialized Java objects to a stream.
PipedOutputStreamConnects to a PipedInputStream to allow thread-to-thread communication.
FilterOutputStreamSuperclass for all output streams that “filter” data, e.g., DataOutputStream and BufferedOutputStream.

✅ Quick Examples

1. FileOutputStream

OutputStream out = new FileOutputStream("output.txt");
out.write("Hello".getBytes());
out.close();

2. BufferedOutputStream

OutputStream out = new BufferedOutputStream(new FileOutputStream("output.txt"));
out.write("Buffered Hello".getBytes());
out.close();

3. ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(65); // 'A'
byte[] data = baos.toByteArray();
System.out.println(Arrays.toString(data)); // [65]

4. DataOutputStream

DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"));
dos.writeInt(42);
dos.writeDouble(3.14);
dos.close();

5. ObjectOutputStream

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"));
oos.writeObject(new MyClass());
oos.close();

🧵 Summary

Stream TypeUse Case
FileOutputStreamWriting to files
BufferedOutputStreamEfficient writing with buffer
DataOutputStreamWriting primitives
ByteArrayOutputStreamWriting to memory
ObjectOutputStreamWriting objects
PipedOutputStreamInter-thread streaming
FilterOutputStreamBase for stream decorators
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.