Java Language Wrapping Input/Output Streams


OutputStream and InputStream have many different classes, each of them with a unique functionality. By wrapping a stream around another, you gain the functionality of both streams.

You can wrap a stream any number of times, just take note of the ordering.

Useful combinations

Writing characters to a file while using a buffer

File myFile = new File("targetFile.txt");
PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(myFile)));

Compressing and encrypting data before writing to a file while using a buffer

Cipher cipher = ... // Initialize cipher
File myFile = new File("targetFile.enc");
BufferedOutputStream outputStream = new BufferedOutputStream(new DeflaterOutputStream(new CipherOutputStream(new FileOutputStream(myFile), cipher)));

List of Input/Output Stream wrappers

BufferedOutputStream/ BufferedInputStreamWhile OutputStream writes data one byte at a time, BufferedOutputStream writes data in chunks. This reduces the number of system calls, thus improving performance.
DeflaterOutputStream/ DeflaterInputStreamPerforms data compression.
InflaterOutputStream/ InflaterInputStreamPerforms data decompression.
CipherOutputStream/ CipherInputStreamEncrypts/Decrypts data.
DigestOutputStream/ DigestInputStreamGenerates Message Digest to verify data integrity.
CheckedOutputStream/ CheckedInputStreamGenerates a CheckSum. CheckSum is a more trivial version of Message Digest.
DataOutputStream/ DataInputStreamAllows writing of primitive data types and Strings. Meant for writing bytes. Platform independent.
PrintStreamAllows writing of primitive data types and Strings. Meant for writing bytes. Platform dependent.
OutputStreamWriterConverts a OutputStream into a Writer. An OutputStream deals with bytes while Writers deals with characters
PrintWriterAutomatically calls OutputStreamWriter. Allows writing of primitive data types and Strings. Strictly for writing characters and best for writing characters