Write CSV output and text reports
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Showing steps for Windows. They are marked “On Windows” below.
Writing CSV is the mirror of reading it: every object becomes one line, and every value that holds a comma or a quote must be quoted so that a reader gets the same value back. Next to the CSV for programs, a neat text report with lined-up columns is what people read.
Escaping commas and quotes when writing
Escaping a value means writing it so that its special characters are read as plain text. For CSV, a value with a comma, a double quote or a line break is wrapped in quotes, and each quote inside is doubled.
Example 1 · csvField quotes only when needed
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;
record Book(String title, String author, int copies) { String toCsv() { return String.join(",", CsvOutDemo.csvField(title), CsvOutDemo.csvField(author), String.valueOf(copies)); }}
public class CsvOutDemo { static String csvField(String value) { if (value.contains(",") || value.contains("\"") || value.contains("\n") || value.contains("\r")) { return "\"" + value.replace("\"", "\"\"") + "\""; } return value; }
public static void main(String[] args) throws IOException { List<Book> books = List.of( new Book("Wings of Fire", "Kalam, A. P. J. Abdul", 3), new Book("The \"Gita\" for Students", "Rao", 1), new Book("Godan", "Premchand", 2));
List<String> lines = new ArrayList<>(); lines.add("title,author,copies"); for (Book b : books) { lines.add(b.toCsv()); } Path file = Path.of("books.csv"); Files.write(file, lines, StandardCharsets.UTF_8);
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) { System.out.println(line); } Files.deleteIfExists(file); }}title,author,copies Wings of Fire,"Kalam, A. P. J. Abdul",3 "The ""Gita"" for Students",Rao,1 Godan,Premchand,2
What this code does
- Only values that need it are quoted: the author with a comma, and the title with quotes, whose inner quotes are doubled.
GodanandPremchandare written as they are. toCsvsends every text field throughcsvField, soString.join(",", ...)cannot produce a line with the wrong number of fields. Numbers have no commas, so they need no quoting.
Example 2 · Round trip: write, read back, compare
import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, String city) { String toCsv() { return roll + "," + RoundTripDemo.csvField(name) + "," + RoundTripDemo.csvField(city); }
static Student fromFields(List<String> f) { return new Student(Integer.parseInt(f.get(0)), f.get(1), f.get(2)); }}
public class RoundTripDemo { static String csvField(String value) { if (value.contains(",") || value.contains("\"") || value.contains("\n") || value.contains("\r")) { return "\"" + value.replace("\"", "\"\"") + "\""; } return value; }
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); } } fields.add(field.toString()); return fields; }
public static void main(String[] args) { List<Student> original = List.of( new Student(101, "Rao, Asha", "Bengaluru"), new Student(102, "Neel \"Sonu\" Shah", "Surat"), new Student(103, "", "Pune, MH"));
int same = 0; for (Student s : original) { String line = s.toCsv(); Student back = Student.fromFields(parseLine(line)); boolean ok = back.equals(s); if (ok) { same++; } System.out.println((ok ? "SAME " : "DIFF ") + line); } System.out.println(same + " of " + original.size() + " records came back unchanged"); }}SAME 101,"Rao, Asha",Bengaluru SAME 102,"Neel ""Sonu"" Shah",Surat SAME 103,,"Pune, MH" 3 of 3 records came back unchanged
What this code does
- Each student is written with
toCsv, read back with the parser from the Quoted fields lesson and compared with recordequals, which checks every field. - Names with commas, quotes and even an empty name all survive. If someone later removes the quoting from
csvField, this check prints DIFF at once.
Put this rule in one small method, csvField(String value), and send every text value through it. Joining fields with String.join(",", ...) is then safe, because no field can add an extra comma. The best test is a round trip: write the records, read the file back with your parser and check that you get the same records. If the name Rao, Asha comes back whole, the escaping works.
Find the bug
Find the CSV writing bug
Each snippet writes CSV. Tap the line that produces a broken file.
A name such as Rao, Asha must stay one field.
Round 1 of 3Aligned text reports with String.format
String.format builds text from a pattern. %-12s is text in at least 12 characters, left-aligned because of the -. %5d is a whole number right-aligned in 5 characters. %7.2f is a decimal with 2 digits after the point, in 7 characters.
Example 3 · A fee report with lined-up columns
import java.util.List;import java.util.Locale;
record Fee(String name, int paid, int due) {}
public class AlignedReportDemo { static final String ROW = "%-14s %8s %8s %7s%n";
public static void main(String[] args) { List<Fee> fees = List.of( new Fee("Asha Rao", 45000, 45000), new Fee("Bhavesh Patel", 30000, 45000), new Fee("Chitra Iyer", 45000, 45000), new Fee("Dev", 12500, 45000));
StringBuilder out = new StringBuilder(); out.append(String.format(Locale.ROOT, ROW, "Name", "Paid", "Due", "Paid %")); out.append("-".repeat(40)).append(System.lineSeparator()); int totalPaid = 0; for (Fee f : fees) { double pct = 100.0 * f.paid() / f.due(); out.append(String.format(Locale.ROOT, "%-14s %8d %8d %6.1f%%%n", f.name(), f.paid(), f.due(), pct)); totalPaid += f.paid(); } out.append("-".repeat(40)).append(System.lineSeparator()); out.append(String.format(Locale.ROOT, "%-14s %8d%n", "Total", totalPaid)); System.out.print(out);
String longName = String.format("%-8s|", "Ramakrishnan"); System.out.println("Width is a minimum: " + longName); }}Name Paid Due Paid % ---------------------------------------- Asha Rao 45000 45000 100.0% Bhavesh Patel 30000 45000 66.7% Chitra Iyer 45000 45000 100.0% Dev 12500 45000 27.8% ---------------------------------------- Total 132500 Width is a minimum: Ramakrishnan|
What this code does
%-14spads names on the right so that the numbers start in the same column;%8dpads numbers on the left so their last digits line up.%%prints a real percent sign and%nends the line.- The last line shows the trap:
Ramakrishnanhas 12 letters, more than the width of 8, so it is printed in full and the|moves right. Choose the width from the longest name you expect.
Use the same pattern for the header and for every row, and the columns line up. "-".repeat(30) draws a line under the header. A width is a minimum, not a maximum. A name longer than the column pushes the rest of the row to the right. Pick widths from the longest expected value, or cut long values with substring.
Locale and decimal points in numbers
A locale is a language and country setting, such as en_IN or de_DE. String.format("%.2f", x) uses the computer's default locale, and in many countries, Germany for example, the decimal mark is a comma: 1234,50.
Example 4 · Trap: a German computer writes a decimal comma
import java.util.Locale;
public class LocaleTrapDemo { public static void main(String[] args) { double average = 78.456;
String german = String.format(Locale.GERMANY, "%.2f", average); String neutral = String.format(Locale.ROOT, "%.2f", average); System.out.println("Germany: " + german); System.out.println("ROOT: " + neutral);
String badLine = "101,Asha," + german; System.out.println(badLine + " -> " + badLine.split(",").length + " fields"); try { Double.parseDouble(german); } catch (NumberFormatException e) { System.out.println("Reading it back: " + e.getMessage()); }
String goodLine = "101,Asha," + neutral; System.out.println(goodLine + " -> " + goodLine.split(",").length + " fields, value " + Double.parseDouble(goodLine.split(",")[2])); }}Germany: 78,46 ROOT: 78.46 101,Asha,78,46 -> 4 fields Reading it back: For input string: "78,46" 101,Asha,78.46 -> 3 fields, value 78.46
What this code does
- The same number becomes
78,46with the German locale. Inside a CSV line it adds a fourth field, andparseDoublecannot read it back. - With
Locale.ROOTthe decimal mark is always a dot, whatever the computer's settings, so the line has 3 fields and the value reads back. The program passesLocale.GERMANYon purpose; a real bug comes from the default locale of the computer it runs on.
In a CSV file that comma becomes a field separator, and Double.parseDouble("1234,50") throws NumberFormatException. The same program writes correct files on one computer and broken files on another. For files that programs read, always pass Locale.ROOT: String.format(Locale.ROOT, "%.2f", x). Locale.ROOT is the neutral locale, with a dot for decimals on every computer. Use the user's locale only for text that people read on screen.
"%.2f".formatted(x) also uses the default locale. String.valueOf(x) and BigDecimal.toPlainString() always use a dot.UTF-8 files that spreadsheets open correctly
Save CSV files as UTF-8, so that names in Hindi, Tamil or with accents and the rupee sign survive. Excel on Windows, though, often opens a UTF-8 CSV with the old Windows character set when you double-click it, and those characters turn into junk.
On Windows
Excel on Windows often opens a UTF-8 CSV with the old Windows character set when you double-click it. Writing the BOM at the start of the file makes names and the rupee sign appear correctly. Open the file by double-click to test it.
Example 5 · Write a BOM for Excel and strip it when reading
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 BomDemo { static final String BOM = "";
public static void main(String[] args) throws IOException { Path file = Path.of("marks-excel.csv"); Files.writeString(file, BOM + "roll,name,marks\n101,Asha,87\n", StandardCharsets.UTF_8);
byte[] bytes = Files.readAllBytes(file); System.out.printf("First bytes: %02X %02X %02X%n", bytes[0], bytes[1], bytes[2]);
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8); String header = lines.get(0); System.out.println("Header length: " + header.length()); System.out.println("Header equals \"roll,name,marks\": " + header.equals("roll,name,marks"));
if (header.startsWith(BOM)) { header = header.substring(1); } System.out.println("After stripping, length " + header.length() + ", equals: " + header.equals("roll,name,marks")); Files.deleteIfExists(file); }}First bytes: EF BB BF Header length: 16 Header equals "roll,name,marks": false After stripping, length 15, equals: true
What this code does
\uFEFFis one character in Java but 3 bytes in UTF-8:EF BB BF. Excel sees these bytes and reads the rest of the file as UTF-8.- Java keeps the BOM when reading, so the header has 16 characters instead of 15 and the header check fails. Removing a leading
\uFEFFfrom the first line fixes it.
The usual fix is a BOM (byte order mark): the invisible character \uFEFF at the very start of the file. In UTF-8 it is the 3 bytes EF BB BF, and Excel takes it as a sign that the file is UTF-8. The BOM has a cost when you read the file back. Java does not remove it, so the first header field becomes \uFEFFroll, which is not equal to roll. Strip it from the first line before you check the header.
Next step
Check your understanding
12 quick questions