๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 3 ยท Lesson 8 of 15

0% Exit to course

Module 3 ยท Exceptions, files and the interview set Lesson 8 of 15

Reading a file and writing a report

Learning objective

Reading a CSV into objects and writing a summary out is the shape of the first task in most enterprise teams. It is also the smallest project that proves you can work in a real codebase.

The concept

The fresher file task is always the same: read a CSV, do something to each row, write a report. Files.readAllLines(Path.of("data.csv")) gives you the lines, splitting each on a comma gives you the fields, and Files.writeString or a BufferedWriter writes the output.

Write it as three methods โ€” read, process, write โ€” and the whole thing becomes testable and explainable in an interview. Handle a missing file with a readable message rather than a stack trace, and skip the blank last line rather than crashing on it, which is what real exports always contain.

Java
Map<String, Integer> totals = new LinkedHashMap<>();
try (BufferedReader r = new BufferedReader(new FileReader("raw.csv"))) {
    r.readLine();                                  // skip the header
    String line;
    while ((line = r.readLine()) != null) {
        String[] cells = line.split(",");
        if (cells.length < 3 || cells[1].isBlank()) continue;
        totals.merge(cells[1].trim(),
                     Integer.parseInt(cells[2].trim()), Integer::sum);
    }
}
try (PrintWriter w = new PrintWriter("report.csv")) {
    totals.forEach((city, n) -> w.println(city + "," + n));
}

Common mistakes

The mistakes are hard-coding an absolute path from your own laptop, and using split(",") on text where a field contains a comma inside quotes. Use line.split(",", -1) so trailing empty fields are kept, and print the first three rows before trusting any of the parsing.

Worked example

Reading line by line with split(",") and building a Student per line gives you a list you can total, sort and print โ€” the same program an MIS team would ask a fresher to write.

Your practice task

Add a malformed line to your CSV on purpose and make the program report the line number and keep going instead of crashing.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

The fresher file task is always the same: read a CSV, do something to each row, write a report.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.

Next recommended course Python for Absolute Beginners