0
0
JavaHow-ToBeginner · 3 min read

How to Write CSV File in Java: Simple Guide with Example

To write a CSV file in Java, use FileWriter combined with BufferedWriter to write text lines separated by commas. Each line represents a row, and commas separate the columns. Remember to close the writer to save the file properly.
📐

Syntax

Use FileWriter to open or create a file, wrap it with BufferedWriter for efficient writing, then write each CSV row as a comma-separated string. Finally, close the writer to save changes.

  • FileWriter fileWriter = new FileWriter("filename.csv"); - opens or creates the CSV file.
  • BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); - buffers writes for performance.
  • bufferedWriter.write("data1,data2,data3"); - writes a CSV row.
  • bufferedWriter.newLine(); - moves to the next line.
  • bufferedWriter.close(); - closes and saves the file.
java
FileWriter fileWriter = new FileWriter("file.csv");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("value1,value2,value3");
bufferedWriter.newLine();
bufferedWriter.close();
💻

Example

This example writes a CSV file named data.csv with three rows and three columns each. It shows how to open the file, write rows with commas, and close the file properly.

java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CsvWriterExample {
    public static void main(String[] args) {
        String fileName = "data.csv";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write("Name,Age,City");
            writer.newLine();
            writer.write("Alice,30,New York");
            writer.newLine();
            writer.write("Bob,25,Los Angeles");
            writer.newLine();
            writer.write("Charlie,35,Chicago");
            writer.newLine();
            System.out.println("CSV file written successfully.");
        } catch (IOException e) {
            System.err.println("Error writing CSV file: " + e.getMessage());
        }
    }
}
Output
CSV file written successfully.
⚠️

Common Pitfalls

Common mistakes when writing CSV files in Java include:

  • Not closing the writer, which can cause data loss.
  • Forgetting to add commas between values, resulting in one long string.
  • Not adding new lines, causing all data to be on one line.
  • Not handling exceptions, which can crash the program if file writing fails.
  • Not escaping commas inside data values, which can break CSV format.

Always use try-with-resources to auto-close writers and handle exceptions.

java
/* Wrong way: missing commas and no new lines */
BufferedWriter writer = new BufferedWriter(new FileWriter("wrong.csv"));
writer.write("Alice 30 New York"); // no commas
writer.close();

/* Right way: commas and new lines */
try (BufferedWriter writer = new BufferedWriter(new FileWriter("right.csv"))) {
    writer.write("Alice,30,New York");
    writer.newLine();
}
📊

Quick Reference

Remember these tips when writing CSV files in Java:

  • Use BufferedWriter with FileWriter for efficient writing.
  • Separate values with commas and rows with new lines.
  • Close the writer to save the file.
  • Use try-with-resources to handle closing automatically.
  • Escape commas inside data if needed by enclosing values in quotes.

Key Takeaways

Use FileWriter and BufferedWriter to write CSV files efficiently in Java.
Separate columns with commas and rows with new lines for proper CSV format.
Always close the writer or use try-with-resources to save the file correctly.
Handle IOExceptions to avoid program crashes during file writing.
Escape commas inside data by enclosing values in quotes if necessary.