Text files: 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 text-file bugs come from four mistakes: reading a huge file all at once, trusting the default charset, splitting on \n by hand, and overwriting when you meant to add. Each one has a short, reliable fix.
Mistake 1: reading a huge file all at once
Files.readAllLines and Files.readString load the whole file into memory. They are perfect for a settings file and wrong for a server log, which can be bigger than the heap and end in OutOfMemoryError. The bug hides in testing, where the sample log is small.
Example 1 · Fix: search a large log line by line
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class LogSearchDemo { public static void main(String[] args) throws IOException { Path log = Path.of("payments.log"); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 100_000; i++) { if (i % 25_000 == 0) { sb.append("WARN upi timeout txn ").append(i).append("\n"); } else { sb.append("INFO upi ok txn ").append(i).append("\n"); } } Files.writeString(log, sb.toString());
String word = "timeout"; int lineNo = 0; int matches = 0; try (BufferedReader in = Files.newBufferedReader(log, StandardCharsets.UTF_8)) { String line; while ((line = in.readLine()) != null) { lineNo++; if (line.contains(word)) { matches++; if (matches <= 2) { System.out.println("line " + lineNo + ": " + line); } } } } System.out.println("Lines read: " + lineNo + ", matches: " + matches);
Files.delete(log); }}line 25000: WARN upi timeout txn 25000 line 50000: WARN upi timeout txn 50000 Lines read: 100000, matches: 4
What this code does
- Only one line is in memory at a time, so the same code searches a 10 GB log.
readAllLineswould have kept all 100,000 lines just to find 4. - The
readLineloop gives line numbers for free, which is what a person fixing the problem needs.Files.lineswithfilterandcountworks too when you need only the count.
The fix is to read line by line: a BufferedReader loop when you need line numbers, or Files.lines with filter and count for quick totals. Both keep only one line in memory and stop as early as you want.
Mistake 2: trusting the default charset
Code that turns bytes into text without naming a charset, such as new String(bytes), getBytes(), FileReader or a Scanner on a file, uses the default. On Java 17 Windows that was windows-1252, so ₹ and Hindi names became ? or garbled symbols.
Example 2 · Fix: a charset bug in an old export
import java.io.IOException;import java.nio.charset.Charset;import java.nio.charset.MalformedInputException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class CharsetFixDemo { public static void main(String[] args) throws IOException { Path old = Path.of("names-export.csv"); Charset win = Charset.forName("windows-1252"); // An old accounts program exported this file in windows-1252 Files.writeString(old, "Ren\u00E9e,92\nZo\u00EB,88\nAsha,79\n", win); // Renée, Zoë
try { Files.readAllLines(old); // assumes UTF-8 } catch (MalformedInputException e) { System.out.println("Wrong charset: " + e.getClass().getSimpleName()); }
List<String> rows = Files.readAllLines(old, win); Path fixed = Path.of("names-utf8.csv"); Files.write(fixed, rows, StandardCharsets.UTF_8);
List<String> check = Files.readAllLines(fixed, StandardCharsets.UTF_8); System.out.println("Rows: " + check.size() + ", first name has " + check.get(0).split(",")[0].length() + " letters"); System.out.println("Same data after conversion: " + check.equals(rows));
Files.delete(old); Files.delete(fixed); }}Wrong charset: MalformedInputException Rows: 3, first name has 5 letters Same data after conversion: true
What this code does
- The error is a hint, not a dead end: the bytes are not UTF-8. Reading with the charset the old program really used gives correct names, with
Renéeas 5 letters. - The fix converts once, at the edge: read old data with its real charset, save it as UTF-8, and let the rest of the program use UTF-8 everywhere.
The opposite case is a file from old software that really is windows-1252: Files.readAllLines reads it as UTF-8 and throws MalformedInputException. The fix in both cases: name the charset on every read and write, and convert old files to UTF-8 once.
Mistake 3: splitting on \n by hand
text.split("\n") leaves a hidden \r at the end of every line of a Windows file, and split(" ") makes empty "words" from double spaces. Counts look almost right, but equals, parseInt and map lookups quietly fail.
Example 3 · Fix: a word and line counter that trusts \n
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.Set;import java.util.TreeSet;
public class WordCounterDemo { public static void main(String[] args) throws IOException { Path file = Path.of("essay.txt"); Files.writeString(file, "Java is fun\r\nfiles are fun\r\nJava\r\n"); // saved on Windows
// Wrong: split by hand on \n and on single spaces String[] rawLines = Files.readString(file).split("\n"); Set<String> wrongWords = new TreeSet<>(); for (String line : rawLines) { for (String word : line.split(" ")) { wrongWords.add(word.toLowerCase()); } } System.out.println("Wrong: " + rawLines.length + " lines, " + wrongWords.size() + " distinct words");
// Right: line methods and a split that ignores extra spaces List<String> lines = Files.readAllLines(file); Set<String> words = new TreeSet<>(); int total = 0; for (String line : lines) { for (String word : line.trim().split(" +")) { if (!word.isEmpty()) { words.add(word.toLowerCase()); total++; } } } System.out.println("Right: " + lines.size() + " lines, " + total + " words, " + words.size() + " distinct: " + words);
Files.delete(file); }}Wrong: 3 lines, 7 distinct words Right: 3 lines, 7 words, 5 distinct: [are, files, fun, is, java]
What this code does
- The wrong version counts
fun\randfunas different words,java\randjavatoo, and the double space adds an empty "word". Seven distinct words for a text that has five. readAllLinesremoves the\r\n, andsplit(" +")treats any run of spaces as one gap. The line count happened to be right in both versions, which is why the bug is easy to miss.
Use the line methods (readAllLines, Files.lines, readLine, lines()) or split("\\R"), and split words with trim().split(" +").
Mistake 4: overwriting when you meant to add
Files.writeString and Files.write truncate the file by default. Called in a loop to build a log or merge files, they keep only the last piece. A BufferedWriter that is never closed has the opposite problem: the file stays empty or ends early.
Example 4 · Fix: merging two files without losing one
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class MergeFilesDemo { public static void main(String[] args) throws IOException { Path a = Path.of("section-a.txt"); Path b = Path.of("section-b.txt"); Path merged = Path.of("all-students.txt"); Files.writeString(a, "Asha\nRavi\n"); Files.writeString(b, "Meena\nKiran\n");
// Wrong: each writeString replaces the whole file for (Path part : List.of(a, b)) { Files.writeString(merged, Files.readString(part)); } System.out.println("Wrong merge: " + Files.readAllLines(merged));
// Right: one writer for the output, one reader per input try (BufferedWriter out = Files.newBufferedWriter(merged, StandardCharsets.UTF_8)) { for (Path part : List.of(a, b)) { try (BufferedReader in = Files.newBufferedReader(part, StandardCharsets.UTF_8)) { String line; while ((line = in.readLine()) != null) { out.write(line); out.write("\n"); } } } } System.out.println("Right merge: " + Files.readAllLines(merged));
Files.delete(a); Files.delete(b); Files.delete(merged); }}Wrong merge: [Meena, Kiran] Right merge: [Asha, Ravi, Meena, Kiran]
What this code does
- The default write options truncate the file, so the second
writeStringwiped out section A.CREATE, APPENDwould also work, but then an old merged file would keep growing on every run. - Opening the output once and copying line by line is fast, keeps memory small for big inputs, and writes
\nendings no matter which system made the input files.
For merging, open one BufferedWriter for the output in try-with-resources and copy each input into it line by line. For a log, use CREATE, APPEND. For an important file, write to a temp file and ATOMIC_MOVE it into place.
Finish up
Mark complete & continue
Next: Bytes and characters