I/O, Serialization & Networking
I/O Streams
InputStream/OutputStream) move raw bytes; the library builds everything else by decorating them — buffering, compression, encryption — one wrapper at a time. Understand the decorator stack and all of java.io falls into place.InputStream/OutputStream: bytes.Reader/Writer: characters (Readers Writers)- Streams are composable decorators: wrap a raw stream to add capability
- Always buffer file and network streams — unbuffered reads are per-byte syscalls
- Close streams with try-with-resources; closing the outermost closes the chain
transferTo(out)copies a whole stream in one call (Java 9+)
try (var in = new DataInputStream(
new BufferedInputStream(
new GZIPInputStream(
Files.newInputStream(path))))) {
// bytes flow: file → gunzip → buffer → typed reads
int magic = in.readInt();
double price = in.readDouble();
}Each wrapper adds one responsibility — the decorator pattern at its best. BufferedInputStream batches syscalls; GZIPInputStream decompresses; DataInputStream adds typed reads. You assemble exactly the pipeline you need, and the same wrappers work over files, sockets, and byte arrays alike.
try (InputStream in = url.openStream();
OutputStream out = Files.newOutputStream(target)) {
in.transferTo(out); // the modern one-liner
}
byte[] all = in.readAllBytes(); // small payloads: slurp