Wrapping InputOutput Streams
suggest changeOutputStream 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
| Wrapper | Description |
|---|---|
| BufferedOutputStream/ BufferedInputStream | While OutputStream writes data one byte at a time, BufferedOutputStream writes data in chunks. This reduces the number of system calls, thus improving performance. |
| DeflaterOutputStream/ DeflaterInputStream | Performs data compression. |
| InflaterOutputStream/ InflaterInputStream | Performs data decompression. |
| CipherOutputStream/ CipherInputStream | Encrypts/Decrypts data. |
| DigestOutputStream/ DigestInputStream | Generates a message digest to verify data integrity. |
| CheckedOutputStream/ CheckedInputStream | Generates a checksum. A checksum is a more trivial version of a message digest. |
| DataOutputStream/ DataInputStream | Allows reading and writing of primitive data types and Strings in a portable binary format. |
| PrintStream | Allows writing of primitive data types and Strings as text. Character encoding uses the platform default. |
| OutputStreamWriter | Converts an OutputStream into a Writer. An OutputStream deals with bytes while Writers deal with characters. |
| PrintWriter | When given an OutputStream, wraps it in an OutputStreamWriter. Allows writing of primitive data types and Strings. Strictly for writing characters. |
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents