Write a CSV File in Java
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.
Java Program
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
Core Logic
Each field is escaped only when necessary, and the fields of a row are joined with commas and ended with a newline.
- 1
escapewraps a field in quotes if it contains a comma or a quote. - 2Quotes inside the field are doubled, so
"becomes"". - 3Each row is built with a
StringBuilderand written followed by\n. - 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.
Why: Every character is written once, and only one row of width w is built at a time.
Key Concepts
Approach 2: Building the File with Streams
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
Core Logic
For simple numeric rows, Collectors.joining can build the whole file — header included — as one string.
- 1Each score pair is mapped to an
id,scoreline. - 2
joining("\n", "id,score\n", "\n")adds the header as a prefix and a final newline as a suffix. - 3
Files.writeStringwrites it in one call.
Key Point: Building the whole file in memory is fine for small exports; write row by row for large ones.
Why: The full file text of length L is held in memory before writing.
Key Concepts
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.