Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization
The previous post only dealt with text; this one looks at the whole java.io class family underneath. Afterwards you’ll know why “reading a file” has five or six spellings, which one to use in real code, and why Java’s built-in serialization is a security risk. This is the last post of the Java basics series; a good next step is OOP.
1. Byte streams and character streams
Key idea: disks and networks only know bytes; characters exist only once bytes are decoded with a charset (an encoding table such as UTF-8). Java splits these two layers into two class families and combines them by wrapping one inside another.
| Byte streams | Character streams | |
|---|---|---|
| Base classes | InputStream / OutputStream |
Reader / Writer |
| Unit | byte (read() returns 0–255, or -1 at the end) |
UTF-16 char (read() returns the char code, or -1 at the end) |
| Used for | Images, audio, video, zip, PDF, any binary data | Text: .txt, .csv, .json, .html |
| File classes | FileInputStream, FileOutputStream |
FileReader, FileWriter |
| Buffered | BufferedInputStream, BufferedOutputStream |
BufferedReader (readLine), BufferedWriter (newLine) |
| Bridge | InputStreamReader (bytes → chars), OutputStreamWriter (chars → bytes) |
The wrapping is the Decorator pattern: each layer adds one capability (buffering, charset decoding, formatting) while keeping the same InputStream/Reader type. Closing the outermost wrapper is enough; it closes the inner ones.
flowchart LR
F["FileInputStream<br/>reads bytes from the file"] --> R["InputStreamReader<br/>decodes bytes → chars as UTF-8"]
R --> B["BufferedReader<br/>reads in blocks, adds readLine()"]
B --> P["Your code"]
// Read text from any InputStream (file, socket, HTTP body) with an explicit charset
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("vi.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
InputStreamReader is where the charset gets applied. A wrong charset throws no exception; it just corrupts data: decode a UTF-8 file as ISO-8859-1 and "Xin chào Việt Nam" turns into "Xin chà o Viá»t Nam".
FileReader/FileWriter before and after Java 11
Before Java 11, FileReader/FileWriter had no charset parameter and always used the platform default, so the same code behaved differently on Windows and Linux. Java 11 added constructors that take a Charset. On older code, wrap an InputStreamReader/OutputStreamWriter with StandardCharsets.UTF_8 as in the example above.
2. Buffering: why reading one byte at a time is slow
Key idea: every one-byte FileInputStream.read() is a system call (a call into the operating system, with a switch from user mode to kernel mode). A buffer fetches 8 KB at a time, so you pay one system call per block instead of one per byte.
- A 20 MB file read byte by byte: about 20 million system calls to read and another 20 million to write.
BufferedInputStreamreads an 8 KB block into RAM; laterread()calls are served from that array, and only an empty buffer goes back to the OS.BufferedOutputStreamfills 8 KB (or waits forflush()/close()) and then writes once.
It’s like shopping: one trip with a full basket instead of a trip per egg.
Which layers a system call goes through (user mode, the kernel, the page cache, DMA), and why byte-by-byte reads stay slow even when the file is already in the page cache, are measured again in I/O models: blocking, epoll and file descriptors.
3. Serialization
Key idea: serialization turns an object into bytes (to write to a file, send over the network, put in a cache); deserialization rebuilds the object from them. Java’s built-in mechanism (ObjectOutputStream/ObjectInputStream) is brittle and dangerous, so default to JSON or Protobuf.
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private transient String password; // not written out
private transient int loginCount = 5; // reads back as 0, not 5
}
try (var out = new ObjectOutputStream(Files.newOutputStream(Path.of("user.bin")))) {
out.writeObject(user);
}
try (var in = new ObjectInputStream(Files.newInputStream(Path.of("user.bin")))) {
User u = (User) in.readObject(); // password = null, loginCount = 0
}
Serializableis a marker interface (an interface with no methods that only tags a class). Every non-transientfield must be serializable too, or you getNotSerializableExceptionat runtime.transientkeeps a field out of the data (passwords, caches, connections). On the way back it holds its default value (null/0/false); neither the initializer nor the constructor runs.serialVersionUIDis the class’s version number. If the number in the data differs from the current class’s, you getInvalidClassException. Always declare it explicitly.- These days you rarely call
ObjectOutputStreamyourself; you meet it indirectly through Spring Session or caches usingJdkSerializationRedisSerializer, RMI, legacy systems.
More on serialVersionUID and exceptions
- If you don’t declare it, the JVM computes one from the class structure, so adding a method or a field may make old data unreadable.
- Any value works (
1Lis common), and different classes sharing the same number is fine; change it only when you deliberately want to break compatibility. - IDEs warn about a missing
serialVersionUIDon custom exceptions becauseThrowableimplementsSerializable, so every exception is serializable.
Records on deserialization: safer than ordinary classes
Exercises
Each prompt is a short paraphrase. All solutions were run on JDK 21.
1. Copy an mp3 file with BufferedInputStream/BufferedOutputStream and time it. Open the source with a FileInputStream wrapped in a BufferedInputStream, the destination with a FileOutputStream wrapped in a BufferedOutputStream, read and write one byte at a time, time it and print Copy completed in XXX ms.
Solution to Exercise 1: three copy methods, two rounds, an identity check
I added the two approaches you’d actually use, for comparison, and check that each copy is identical to the original.
import java.io.*;
import java.nio.file.*;
public class CopyTimer {
// What the task asks for: wrap in buffers, then copy byte by byte
static void copyByteByByte(Path src, Path dst) throws IOException {
try (InputStream in = new BufferedInputStream(new FileInputStream(src.toFile()));
OutputStream out = new BufferedOutputStream(new FileOutputStream(dst.toFile()))) {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
} // BufferedOutputStream.close() flushes whatever is left in the buffer
}
// What to use when you have to copy between two streams
static void copyWithTransferTo(Path src, Path dst) throws IOException {
try (InputStream in = Files.newInputStream(src);
OutputStream out = Files.newOutputStream(dst)) {
in.transferTo(out);
}
}
static void time(String label, Path src, Path dst, IOAction action) throws IOException {
long start = System.nanoTime(); // nanoTime measures elapsed time; currentTimeMillis is wall-clock time and can jump
action.run(src, dst);
long ms = (System.nanoTime() - start) / 1_000_000;
boolean same = Files.mismatch(src, dst) == -1; // Java 12: -1 means the files are identical
System.out.printf("%-22s %6d ms, identical: %b%n", label, ms, same);
}
interface IOAction { void run(Path src, Path dst) throws IOException; }
public static void main(String[] args) throws IOException {
Path src = Path.of("input.mp3");
System.out.println("Size: " + Files.size(src) + " bytes");
for (int round = 1; round <= 2; round++) { // two rounds: the first one also pays for JIT warm-up and the page cache
System.out.println("Round " + round);
time("buffered, byte by byte", src, Path.of("copy1.mp3"), CopyTimer::copyByteByByte);
time("transferTo", src, Path.of("copy2.mp3"), CopyTimer::copyWithTransferTo);
time("Files.copy", src, Path.of("copy3.mp3"),
(s, d) -> Files.copy(s, d, StandardCopyOption.REPLACE_EXISTING));
}
}
}
20 MB file, JDK 21, my machine: round 1 took 230 ms / 7 ms / 4 ms, round 2 took 140 ms / 3 ms / 3 ms; all three copies were identical to the original.
- The first round is slower because the JIT hasn’t compiled the loop yet and the file isn’t in the page cache. A single measurement can’t be trusted; for serious measurements use JMH.
- The task uses
System.currentTimeMillis(). For elapsed time, preferSystem.nanoTime():currentTimeMillisis wall-clock time and can jump when NTP adjusts the clock. - The code in the original material doesn’t close its streams on failure (and has a stray
)), so it leaks file descriptors if the copy fails halfway. try-with-resources fixes that. - A senior would just write
Files.copy(src, dst)for file to file andin.transferTo(out)for stream to stream, and would check free disk space or write to a temp file and rename it if someone may be reading the target.
2. Read and write a small binary file with Files.
byte[] data = Files.readAllBytes(Path.of("logo.png")); // the whole file in memory: small files only
System.out.println(data.length + " bytes, first byte = " + data[0]); // signed byte: 0x89 prints as -119
Files.write(Path.of("sample.bin"), new byte[]{10, 20, 30, 40, 50});
Java’s byte is signed (-128 to 127), so the 0x89 that starts every PNG file prints as -119. For a 0–255 value, use Byte.toUnsignedInt(data[0]) or data[0] & 0xFF.
Remember
- Can you explain when to use a byte stream versus a
Reader/Writer, and where the charset gets applied? - Can you draw the Decorator chain
FileInputStream→InputStreamReader→BufferedReader? - Can you explain why byte-by-byte reads are slow, and choose between
Files.copyandtransferTo? - Can you say what
serialVersionUIDandtransientdo, and what atransientfield holds after reading back? - Can you explain a gadget chain, and what replaces Java serialization or how
ObjectInputFilterlimits it?
Interview questions
Junior
What’s the difference between byte streams and character streams, and when do you use each?
Byte streams read and write raw bytes for binary data; character streams work with decoded characters and are meant for text.
Byte streams (InputStream/OutputStream) suit images, audio, zip files. Character streams (Reader/Writer) decode through a charset. InputStreamReader/OutputStreamWriter bridge the two, and you should always pass an explicit charset (StandardCharsets.UTF_8).
What is a marker interface? Does Serializable have any methods?
A marker interface has no methods; it just tags a class with a capability. Serializable has none.
The JVM or a library checks the tag at runtime: ObjectOutputStream checks instanceof Serializable and throws NotSerializableException if it’s missing. Cloneable works the same way. Today annotations usually serve this purpose, because they can carry extra information.
Mid
Why is copying a file with byte-by-byte read() slow? How does BufferedInputStream help? Can available() tell you the file size?
Each read() is a system call; a buffer fetches 8 KB at a time to cut the number of calls. available() does not give you the file size.
A 20 MB file costs tens of millions of switches into the kernel. BufferedInputStream reads 8 KB blocks into RAM and serves later read() calls from there. In real code, use in.transferTo(out) or Files.copy. available() is only an estimate of the bytes readable without blocking; it’s an int capped at 2 GB and is usually 0 for sockets. Get the file size with Files.size.
What are serialVersionUID and transient for?
serialVersionUID is a class’s version number, checked for compatibility on read; transient keeps a field out of the serialized data.
If the number in the data differs from the current class’s, you get InvalidClassException. If you don’t declare it, the JVM derives one from the class structure, so a small change breaks compatibility; declare it explicitly. A transient field (password, cache, connection) reads back with its default value, and its initializer doesn’t run.
Why are java.io classes wrapped in so many layers?
It’s the Decorator pattern: each layer adds exactly one capability while keeping the same type (InputStream or Reader).
FileInputStream reads bytes from a file, BufferedInputStream adds a buffer, InputStreamReader adds charset decoding, BufferedReader adds readLine. That lets you combine them freely (buffering for a socket, GZIPInputStream for a compressed HTTP body) without a dedicated class for every combination. Closing the outermost layer is enough; it closes the chain inward.
Senior
Why is Java serialization considered a security risk, and what do you use instead?
Because readObject() instantiates any class on the classpath named in the data and runs its hooks before your cast, so a gadget chain can achieve remote code execution. Use JSON or Protobuf/Avro instead.
On top of that, the format is Java-only, brittle when classes change, and bulky. With Jackson, keep polymorphic default typing off. If you’re stuck with it, set an allow-list with ObjectInputFilter (JEP 290), and prefer records, which go through the canonical constructor on deserialization.
How do you correctly measure how long a file copy (or any piece of code) takes?
Use System.nanoTime(), run many iterations with a warm-up, and use JMH for micro-benchmarks.
currentTimeMillis() can jump when the clock is adjusted; nanoTime is a monotonic clock. Discard the first runs so the JIT can compile the code; for I/O, also mind the OS page cache (a second read never touches the disk). Measure on hardware and a filesystem like production’s. JMH handles warm-up, forks the JVM and stops the JIT from eliminating “unused” code. Report a distribution (p50, p99), not just one average.
Useful phrases for interviews
- “Buffering cuts the number of system calls from one per byte to one per block.”
- “I wouldn’t deserialize untrusted data with Java serialization; I’d use JSON with a fixed schema instead.”
- “
java.iofollows the Decorator pattern: each wrapper adds one capability, like buffering or decoding.” - “
Serializableis just a marker interface; the stream checks for it at runtime.” - “I mark secrets as
transientso they never end up in the serialized form.” - “For timing I use
System.nanoTimeand a proper warm-up, or JMH for anything serious.” - “Bumping
serialVersionUIDis a deliberate way to break backward compatibility.” - “For a plain file copy I just call
Files.copyand let the OS do the heavy lifting.”
Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.