CSV and structured text: 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 bugs in programs that read and write text files come from trusting the data. The code assumes every line is clean, every id matches, no value is quoted and every setting is present. Each mistake below has a short, reliable fix.
Mistake 1: trusting a marks file to be clean
A program tested on a tidy file meets a real one: spaces after commas, a blank last line, a quoted name with a comma, a row with missing marks. Plain split(",") plus parseInt crashes on the first surprise, and the whole report is lost.
Example 1 · Marks file to grade report, done safely
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;import java.util.Locale;
record Student(int roll, String name, int marks) {}
public class GradeReportDemo { static List<String> parseLine(String line) { List<String> fields = new ArrayList<>(); StringBuilder field = new StringBuilder(); boolean inQuotes = false; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (inQuotes) { if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; } else if (c == '"') { inQuotes = false; } else { field.append(c); } } else if (c == ',') { fields.add(field.toString()); field.setLength(0); } else if (c == '"' && field.length() == 0) { inQuotes = true; } else { field.append(c); } } if (inQuotes) { throw new IllegalArgumentException("Unclosed quote in: " + line); } fields.add(field.toString()); return fields; }
static String grade(int marks) { if (marks >= 85) return "A"; if (marks >= 70) return "B"; if (marks >= 35) return "C"; return "F"; }
public static void main(String[] args) throws IOException { Path file = Path.of("marks.csv"); Files.writeString(file, "roll,name,marks\n101,\"Rao, Asha\",87\n102, Bhavesh Patel, 64\n" + "103,Chitra Iyer,\n104,Dev Sharma,31\n105,\"Iyer, Esha\",92\n\n", StandardCharsets.UTF_8);
try { for (String line : Files.readAllLines(file, StandardCharsets.UTF_8).subList(1, 3)) { Integer.parseInt(line.split(",")[2].trim()); } } catch (NumberFormatException e) { System.out.println("Naive split: " + e.getMessage()); }
List<Student> students = new ArrayList<>(); List<String> errors = new ArrayList<>(); List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8); for (int i = 1; i < lines.size(); i++) { String line = lines.get(i); if (line.isBlank()) continue; List<String> f = parseLine(line); String marks = f.size() == 3 ? f.get(2).trim() : ""; if (f.size() != 3 || !marks.matches("\\d+")) { errors.add("line " + (i + 1) + ": marks missing or not a number"); continue; } students.add(new Student(Integer.parseInt(f.get(0).trim()), f.get(1).trim(), Integer.parseInt(marks))); }
System.out.println(String.format("%-14s %5s %5s", "Name", "Marks", "Grade")); System.out.println("-".repeat(26)); int total = 0; for (Student s : students) { System.out.println(String.format("%-14s %5d %5s", s.name(), s.marks(), grade(s.marks()))); total += s.marks(); } System.out.println(String.format(Locale.ROOT, "Average of %d: %.1f", students.size(), (double) total / students.size())); errors.forEach(e -> System.out.println("Skipped " + e)); Files.deleteIfExists(file); }}Naive split: For input string: "Asha"" Name Marks Grade -------------------------- Rao, Asha 87 A Bhavesh Patel 64 C Dev Sharma 31 F Iyer, Esha 92 A Average of 4: 68.5 Skipped line 4: marks missing or not a number
What this code does
- The naive version splits
"Rao, Asha"at its comma, so index 2 holdsAsha"andparseIntfails on the very first row. - The safe version uses the quote-aware parser, skips the blank last line, reports Chitra's missing marks with line 4, and still prints the report for the four good rows.
The fix is the full pipeline from this module. Read with UTF-8, skip the header and blank lines, and parse each line with a quote-aware parser. Validate each field, collect bad rows with their line numbers, and only then build the report from the good rows.
Mistake 2: merging two files with nested loops
To join a students file and a fees file on roll number, beginners often loop over every student and, inside, over every fee row. That takes students × fees steps, and it quietly ignores fee rows whose roll matches no student.
Example 2 · Merge students and fees by roll number
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeSet;
public class MergeByIdDemo { public static void main(String[] args) { List<String> studentsCsv = List.of("roll,name", "101,Asha", "102,Bhavesh", "103,Chitra", "104,Dev"); List<String> feesCsv = List.of("roll,paid", "101,45000", "103,30000", "104,45000", "140,45000");
Map<Integer, Integer> paidByRoll = new LinkedHashMap<>(); for (String line : feesCsv.subList(1, feesCsv.size())) { String[] f = line.split(",", -1); paidByRoll.put(Integer.parseInt(f[0].trim()), Integer.parseInt(f[1].trim())); }
TreeSet<Integer> unmatchedFees = new TreeSet<>(paidByRoll.keySet()); System.out.println(String.format("%-5s %-8s %7s", "Roll", "Name", "Paid")); for (String line : studentsCsv.subList(1, studentsCsv.size())) { String[] f = line.split(",", -1); int roll = Integer.parseInt(f[0].trim()); Integer paid = paidByRoll.get(roll); unmatchedFees.remove(roll); System.out.println(String.format("%-5d %-8s %7s", roll, f[1].trim(), paid == null ? "MISSING" : paid)); } System.out.println("Fee rows with no student: " + unmatchedFees); }}Roll Name Paid 101 Asha 45000 102 Bhavesh MISSING 103 Chitra 30000 104 Dev 45000 Fee rows with no student: [140]
What this code does
- The fees file goes into a map once; each student then needs a single
getinstead of a loop over every fee row. Bhavesh has no fee row, so he showsMISSING. - Every roll found in the student file is removed from
unmatchedFees. What is left, roll 140, is a fee paid against a roll number that does not exist, which is probably a typing mistake, such as 104 typed as 140.
The fix is to load one file into a Map keyed by id, then go through the other file once and look each id up. Ids found in only one file are collected and reported, because they almost always mean a typing mistake or a missing row.
Mistake 3: a parser that was never tested on hard lines
A home-made parser that toggles a flag on every quote looks right on "Rao, Asha", but loses doubled quotes, and one that calls trim() on every field removes spaces that were inside the quotes on purpose.
Example 3 · Find the parser bugs with a test table, then fix them
import java.util.ArrayList;import java.util.List;import java.util.function.Function;
public class ParserBugHuntDemo { static List<String> buggyParse(String line) { List<String> out = new ArrayList<>(); StringBuilder f = new StringBuilder(); boolean q = false; for (char c : line.toCharArray()) { if (c == '"') { q = !q; // bug 1: "" toggles twice, the quote is lost } else if (c == ',' && !q) { out.add(f.toString().trim()); // bug 2: trim also removes quoted spaces f.setLength(0); } else { f.append(c); } } out.add(f.toString().trim()); return out; }
static List<String> parseLine(String line) { List<String> fields = new ArrayList<>(); StringBuilder field = new StringBuilder(); boolean inQuotes = false; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (inQuotes) { if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; } else if (c == '"') { inQuotes = false; } else { field.append(c); } } else if (c == ',') { fields.add(field.toString()); field.setLength(0); } else if (c == '"' && field.length() == 0) { inQuotes = true; } else { field.append(c); } } if (inQuotes) { throw new IllegalArgumentException("Unclosed quote in: " + line); } fields.add(field.toString()); return fields; }
static void runTests(String label, Function<String, List<String>> parser) { String[][] cases = { {"\"Rao, Asha\",87", "Rao, Asha|87"}, {"\"5\"\" screen\",TV", "5\" screen|TV"}, {"\" padded \",x", " padded |x"}, {"a,,c", "a||c"} }; int fails = 0; for (String[] c : cases) { String actual = String.join("|", parser.apply(c[0])); if (!actual.equals(c[1])) { fails++; System.out.println(" FAIL " + c[0] + " gave " + actual); } } System.out.println(label + ": " + (cases.length - fails) + " of " + cases.length + " passed"); }
public static void main(String[] args) { runTests("buggy parser", ParserBugHuntDemo::buggyParse); runTests("fixed parser", ParserBugHuntDemo::parseLine); }}FAIL "5"" screen",TV gave 5 screen|TV FAIL " padded ",x gave padded|x buggy parser: 2 of 4 passed fixed parser: 4 of 4 passed
What this code does
- The same four cases run against both parsers. The buggy one passes the easy quoted comma but fails the doubled quote and the padded value, which points straight at its two bugs.
- The fixed parser checks for
""before closing the quotes and never trims, so all four cases pass. Trimming, when wanted, belongs infromCsvfor unquoted number fields, not in the parser.
The fix starts with a test table of tricky lines, not with the code. Run it, read which cases FAIL, fix the parser one rule at a time and keep the table so the bug never comes back.
Mistake 4: a settings loader with no defaults
Integer.parseInt(props.getProperty("max.errors")) fails with NumberFormatException: Cannot parse null string when the key is missing, and with a confusing message when the value has a trailing space. Loading with load(InputStream) also garbles any non-English value.
Example 4 · A settings loader that survives missing and messy values
import java.io.IOException;import java.io.Reader;import java.io.StringReader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.Properties;
record ReportSettings(String title, int maxErrors, String outputFolder) {}
public class SettingsLoaderDemo { static int intSetting(Properties p, String key, int def) { String text = p.getProperty(key); if (text == null) { return def; } try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException(key + " must be a whole number, but is '" + text + "'"); } }
static ReportSettings load(Path file) throws IOException { Properties p = new Properties(); try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { p.load(in); } catch (NoSuchFileException e) { System.out.println("(no " + file.getFileName() + ", using defaults)"); } return new ReportSettings( p.getProperty("report.title", "Marks Report").trim(), intSetting(p, "import.max.errors", 10), p.getProperty("report.folder", "reports").trim()); }
public static void main(String[] args) throws IOException { Properties p = new Properties(); p.load(new StringReader("import.max.errors=5 \n")); try { Integer.parseInt(p.getProperty("report.pages")); } catch (NumberFormatException e) { System.out.println("Naive missing key: " + e.getMessage()); } try { Integer.parseInt(p.getProperty("import.max.errors")); } catch (NumberFormatException e) { System.out.println("Naive trailing space: " + e.getMessage()); }
Path file = Path.of("report.properties"); Files.deleteIfExists(file); System.out.println(load(file)); Files.writeString(file, "report.title = Semester 3 Results \nimport.max.errors=5 \n", StandardCharsets.UTF_8); System.out.println(load(file)); Files.deleteIfExists(file); }}Naive missing key: Cannot parse null string Naive trailing space: For input string: "5 " (no report.properties, using defaults) ReportSettings[title=Marks Report, maxErrors=10, outputFolder=reports] ReportSettings[title=Semester 3 Results, maxErrors=5, outputFolder=reports]
What this code does
- The naive calls show both failures: a missing key gives
null, andparseInt(null)saysCannot parse null string; a trailing space givesFor input string: "5 ". - The loader returns defaults with no file, trims every value, and gives typed settings in a record. The rest of the program never sees
Propertiesor raw text.
The fix: load with a UTF-8 Reader, treat a missing file as "use defaults", read every key with a default, trim() before converting, and throw a message that names the key when a value is really wrong.
Finish up
Mark complete & continue
Next: What serialization means