Java Programs›File Handling›Write a CSV File

Write a CSV File in Java

beginner·  File Handling  ·  File I/O

Problem

When writing CSV, a field containing a comma or a quote must be wrapped in quotes, and any quote inside it is written twice.

Write a small contact list to a CSV file, including a city with a comma and a note with quotes, then print the file.

Input
Ravi, "Delhi, NCR", said "call after 5"
Output
Ravi,"Delhi, NCR","said ""call after 5"""

Java Program

Java
import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class WriteCsvFile { static String escape(String field) { // Fields containing a comma or quote are wrapped in quotes, and quotes are doubled (RFC 4180 style) if (field.contains(",") || field.contains("\"")) { return "\"" + field.replace("\"", "\"\"") + "\""; } return field; } public static void main(String[] args) throws IOException { String[][] rows = { {"name", "city", "note"}, {"Asha", "Pune", "prefers email"}, {"Ravi", "Delhi, NCR", "said \"call after 5\""} }; Path csv = Paths.get("contacts.csv"); try (BufferedWriter out = Files.newBufferedWriter(csv)) { for (String[] row : rows) { StringBuilder line = new StringBuilder(); for (int i = 0; i < row.length; i++) { if (i > 0) line.append(','); line.append(escape(row[i])); } out.write(line.toString()); out.write("\n"); // fixed line ending, so the file is identical on every OS } } System.out.print(Files.readString(csv)); Files.delete(csv); } }

Output

name,city,note Asha,Pune,prefers email Ravi,"Delhi, NCR","said ""call after 5"""

Core Logic

Each field is escaped only when necessary, and the fields of a row are joined with commas and ended with a newline.

How It Works
  1. 1escape wraps a field in quotes if it contains a comma or a quote.
  2. 2Quotes inside the field are doubled, so " becomes "".
  3. 3Each row is built with a StringBuilder and written followed by \n.
  4. 4The file is read back and printed to show the result.
Delhi, NCR is written as "Delhi, NCR", so a CSV reader keeps it as one field.
💡

Key Point: Writing \n explicitly instead of the platform line separator makes the file identical on Windows, macOS and Linux.

Complexity
Time Complexity: O(L)Space Complexity: O(w)

Why: Every character is written once, and only one row of width w is built at a time.

Key Concepts

Files.newBufferedWriter()CSV escapingStringBuilder

Approach 2: Building the File with Streams

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class WriteCsvFileStream { public static void main(String[] args) throws IOException { List<int[]> scores = Arrays.asList(new int[]{101, 88}, new int[]{102, 93}, new int[]{103, 79}); Path csv = Paths.get("scores.csv"); String body = scores.stream() .map(s -> s[0] + "," + s[1]) .collect(Collectors.joining("\n", "id,score\n", "\n")); // header as prefix Files.writeString(csv, body); System.out.print(Files.readString(csv)); System.out.println("Rows written: " + (Files.readAllLines(csv).size() - 1)); Files.delete(csv); } }

Output

id,score 101,88 102,93 103,79 Rows written: 3

Core Logic

For simple numeric rows, Collectors.joining can build the whole file — header included — as one string.

How It Works
  1. 1Each score pair is mapped to an id,score line.
  2. 2joining("\n", "id,score\n", "\n") adds the header as a prefix and a final newline as a suffix.
  3. 3Files.writeString writes it in one call.
Three data rows are written under the header.
💡

Key Point: Building the whole file in memory is fine for small exports; write row by row for large ones.

Complexity
Time Complexity: O(L)Space Complexity: O(L)

Why: The full file text of length L is held in memory before writing.

Key Concepts

Collectors.joining()prefix as headerFiles.writeString()

Interview Questions

Why might Excel show your CSV with garbled characters?

Excel may assume a legacy encoding. Writing a UTF-8 byte-order mark at the start, or opening the file through Excel's import dialog, fixes accented and non-English text.

How do you write a CSV with a semicolon separator?

Use ; instead of , between fields and in the quoting rule — common in countries where the comma is the decimal separator.

Learn the Concept

Related Programs