Byte and character streams: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most stream bugs come from a few habits: ignoring the count that read returns, sending binary data through a Reader, and forgetting to close a buffered stream. Each one leaves a file that looks almost right, and each has a short, reliable fix.
Mistake 1: ignoring the count from read
read(buf) returns how many bytes it put into the buffer, and the last block is almost always partly old data. out.write(buf) copies those stale bytes too, so the copy is bigger than the original.
Example 1 · Mistake 1: a copy that ignores the count, and the fix
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Arrays;
public class CountMistakeDemo { static byte[] copyWrong(byte[] data) throws IOException { ByteArrayOutputStream copy = new ByteArrayOutputStream(); try (InputStream in = new ByteArrayInputStream(data); OutputStream out = copy) { byte[] buf = new byte[4096]; while (in.read(buf) != -1) { out.write(buf); // writes stale bytes on the last block } } return copy.toByteArray(); }
static byte[] copyRight(byte[] data) throws IOException { ByteArrayOutputStream copy = new ByteArrayOutputStream(); try (InputStream in = new ByteArrayInputStream(data); OutputStream out = copy) { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf)) != -1) { out.write(buf, 0, n); } } return copy.toByteArray(); }
public static void main(String[] args) throws IOException { byte[] photo = new byte[10000]; for (int i = 0; i < photo.length; i++) { photo[i] = (byte) (i * 7); } byte[] wrong = copyWrong(photo); byte[] right = copyRight(photo); System.out.println("Wrong: " + wrong.length + " bytes, identical: " + Arrays.equals(photo, wrong)); System.out.println("Fixed: " + right.length + " bytes, identical: " + Arrays.equals(photo, right)); }}Wrong: 12288 bytes, identical: false Fixed: 10000 bytes, identical: true
What this code does
- The wrong loop writes three full 4096-byte buffers, so 2288 stale bytes from the second block end up at the end of the copy.
- Keeping the count
nand writingwrite(buf, 0, n)gives an exact copy. A test with a file smaller than the buffer would not catch this bug, so test with a size that is not a multiple of the buffer.
The fix is the standard loop: keep the count in an int and write out.write(buf, 0, n). Or skip the loop and use in.transferTo(out) or Files.copy.
A related mistake is storing read() in a byte: the copy stops early at the first byte 255.
Mistake 2: binary data through a Reader or Writer
A Reader decodes bytes into characters. Bytes that are not valid text in the charset are replaced by U+FFFD, which the Writer then saves as 3 different bytes. The copied photo grows and never opens again, and the damage cannot be undone.
Example 2 · Mistake 2: copying a photo through a Reader, and the fix
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Reader;import java.io.Writer;import java.nio.charset.StandardCharsets;import java.util.Arrays;
public class ReaderMistakeDemo { public static void main(String[] args) throws IOException { byte[] photo = new byte[1000]; for (int i = 0; i < photo.length; i++) { photo[i] = (byte) i; }
ByteArrayOutputStream viaText = new ByteArrayOutputStream(); try (Reader in = new InputStreamReader(new ByteArrayInputStream(photo), StandardCharsets.UTF_8); Writer out = new OutputStreamWriter(viaText, StandardCharsets.UTF_8)) { in.transferTo(out); }
ByteArrayOutputStream viaBytes = new ByteArrayOutputStream(); try (InputStream in = new ByteArrayInputStream(photo)) { in.transferTo(viaBytes); }
System.out.println("Through a Reader: " + viaText.size() + " bytes, identical: " + Arrays.equals(photo, viaText.toByteArray())); System.out.println("Through bytes: " + viaBytes.size() + " bytes, identical: " + Arrays.equals(photo, viaBytes.toByteArray())); }}Through a Reader: 1976 bytes, identical: false Through bytes: 1000 bytes, identical: true
What this code does
- 488 of these 1000 bytes are 128 or more and not valid UTF-8 on their own. Each became U+FFFD and was written back as 3 bytes, so the copy grew to 1000 + 488 × 2 = 1976 bytes.
- The byte-stream copy uses the same one-line
transferTo, but never decodes anything, so every byte arrives unchanged.
The fix: images, PDFs, ZIP files and anything you cannot read in Notepad go through InputStream and OutputStream only. Readers and Writers are for text, with a named charset.
Mistake 3: a buffered stream that is never closed
A buffered stream keeps up to 8 KB in memory. If it is never closed, that last part never reaches the file, and the JVM does not flush it for you when the program ends.
Example 3 · Mistake 3: an unclosed buffered stream, and the fix
import java.io.BufferedOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;
public class UnclosedMistakeDemo { static OutputStream leaked;
static void saveWrong(Path file, byte[] data) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile())); for (byte b : data) { out.write(b); } leaked = out; // never closed }
static void saveRight(Path file, byte[] data) throws IOException { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))) { for (byte b : data) { out.write(b); } } }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("unclosed"); byte[] marks = new byte[20000]; Path wrong = dir.resolve("marks-wrong.bin"); Path right = dir.resolve("marks-right.bin"); saveWrong(wrong, marks); saveRight(right, marks); System.out.println(wrong.getFileName() + ": " + Files.size(wrong) + " of 20000 bytes"); System.out.println(right.getFileName() + ": " + Files.size(right) + " of 20000 bytes");
leaked.close(); // only so the demo can delete its files Files.delete(wrong); Files.delete(right); Files.delete(dir); }}marks-wrong.bin: 16384 of 20000 bytes marks-right.bin: 20000 of 20000 bytes
What this code does
- Two full 8192-byte blocks reached the disk; the last 3616 bytes were still in the buffer when
saveWrongreturned. Had the program ended there, they would be gone. saveRightdeclares the stream in try-with-resources, socloseflushes the last block. The demo closes the leaked stream at the end only so that Windows lets it delete the file.
On Windows the open file also stays locked, so it cannot be moved or deleted.
The fix is try-with-resources on the outermost stream of the chain. Closing it flushes the buffer and closes every layer underneath.
Choosing the right stream chain
Pick the chain from two questions: is the data bytes or text, and do you need lines, formatting or Java values? Build it from the inside out, starting with the stream that touches the file, keyboard or network.
Example 4 · Four jobs, four chains
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class ChainChoiceDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("chains");
Path photo = Files.write(dir.resolve("id.jpg"), new byte[3000]); Files.copy(photo, dir.resolve("id-copy.jpg")); System.out.println("1. Copied id.jpg: " + Files.size(dir.resolve("id-copy.jpg")) + " bytes");
Path csv = Files.writeString(dir.resolve("marks.csv"), "Asha,82\nRavi,67\n", StandardCharsets.UTF_8); int total = 0; try (InputStream raw = Files.newInputStream(csv); BufferedReader reader = new BufferedReader(new InputStreamReader(raw, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { total += Integer.parseInt(line.split(",")[1]); } } System.out.println("2. Total marks from marks.csv: " + total);
Path report = dir.resolve("report.txt"); try (PrintWriter out = new PrintWriter(report.toFile(), StandardCharsets.UTF_8)) { out.printf("%-6s%4d%n", "Total", total); if (out.checkError()) { throw new IOException("Could not write report.txt"); } } System.out.println("3. report.txt says: " + Files.readString(report).trim());
Path data = dir.resolve("marks.dat"); try (DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(data.toFile())))) { out.writeInt(82); out.writeInt(67); } try (DataInputStream in = new DataInputStream( new BufferedInputStream(new FileInputStream(data.toFile())))) { System.out.println("4. marks.dat (" + Files.size(data) + " bytes): " + in.readInt() + ", " + in.readInt()); }
try (var files = Files.list(dir)) { for (Path p : files.toList()) { Files.delete(p); } } Files.delete(dir); }}1. Copied id.jpg: 3000 bytes 2. Total marks from marks.csv: 149 3. report.txt says: Total 149 4. marks.dat (8 bytes): 82, 67
What this code does
- Each job gets the smallest chain that does it:
Files.copyfor raw bytes, a bridge plusBufferedReaderfor text lines,PrintWriterfor formatted output and data streams for Java values. - Every chain is opened in try-with-resources, so all files are closed before the clean-up at the end deletes them.
- Copy any file as it is:
InputStream→OutputStreamwith a buffer loop,transferToorFiles.copy. - Read text lines from bytes:
BufferedReader→InputStreamReader(in, UTF_8)→ the byte source. - Write a formatted report:
PrintWriteron a file with UTF-8, then checkcheckError(). - Save Java values compactly:
DataOutputStream→BufferedOutputStream→FileOutputStream.
Finish up
Mark complete & continue
Next: Turn a CSV line into a record