Java Write to CSV File: Practical Techniques

Learn practical techniques to write data to CSV in Java, using standard IO and popular libraries like Apache Commons CSV and OpenCSV. Includes step-by-step code examples, best practices, and tips for encoding and escaping.

MyDataTables
MyDataTables Team
·5 min read
Quick AnswerSteps

Writing to a CSV file in Java can be done with standard IO or with CSV libraries. A safe, portable approach uses try-with-resources to auto-close streams, writes a header row, and then iterates data rows while escaping commas and quotes. For larger projects, libraries like Apache Commons CSV or OpenCSV simplify formatting and escaping.

Getting Started with CSV Writing in Java

CSV is a ubiquitous data interchange format and Java provides multiple paths to generate CSV files. For simple needs, you can rely on the standard library with basic escaping. For production-grade CSV writing, use libraries like Apache Commons CSV or OpenCSV to handle edge cases, encoding, and escaping reliably. This section demonstrates a minimal, readable approach with the JDK and then expands to libraries that reduce boilerplate.

Java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class CsvWriterDemo { public static void main(String[] args) throws IOException { String path = "output.csv"; List<String[]> rows = List.of( new String[]{"Name","Age","City"}, new String[]{"Alice","30","New York"}, new String[]{"Bob","25","London"} ); try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) { for (String[] row : rows) { writer.write(String.join(",", escape(row))); writer.newLine(); } } } // Minimal escaping: quotes around fields containing comma or quote, with doubled quotes private static String[] escape(String[] row) { String[] out = new String[row.length]; for (int i = 0; i < row.length; i++) { String val = row[i]; if (val.contains(",") || val.contains("\"")) { val = val.replace("\"", "\"\""); out[i] = "\"" + val + "\""; } else { out[i] = val; } } return out; } }
  • This approach teaches the core idea: header row, row iteration, and escaping. It is suitable for tiny datasets but quickly becomes verbose as requirements grow.
  • Alternatives exist that reduce boilerplate, such as library-based writers that automate escaping and quoting.
  • Variations: use a different delimiter, or stream data from a file or database rather than a hard-coded list.

lineBreaksBetweenParagraphs": true},

Steps

Estimated time: 25-40 minutes

  1. 1

    Choose either standard IO or a library

    Decide if you want a quick, self-contained example using java.io classes or a robust solution via a library like Apache Commons CSV or OpenCSV. Libraries reduce escaping errors and improve maintainability.

    Tip: If you expect future changes to CSV format, start with a library to avoid reworking escaping.
  2. 2

    Set up a data source

    Prepare the data you will write. This can be a List of arrays, a stream of beans converted to rows, or a database cursor. The example uses List<String[]> for clarity.

    Tip: Keep your data structure stable to simplify writing logic.
  3. 3

    Open a writer with try-with-resources

    Use try-with-resources to ensure the writer is closed automatically, preventing resource leaks.

    Tip: Avoid manual close calls in finally blocks; it’s error-prone.
  4. 4

    Write header and rows

    Write the header first, then iterate rows, applying escaping as needed. For libraries, this is typically a single print/record call per row.

    Tip: Validate the output with a small test file before large runs.
  5. 5

    Close the stream and verify output

    Let the try-with-resources block finish, then verify the produced CSV with a text editor or a quick parser.

    Tip: Check for proper newline handling across platforms.
Warning: Do not concatenate CSV values directly; use a CSV library or proper escaping to avoid broken formats.
Pro Tip: Prefer UTF-8 encoding to support international characters in headers and data.
Note: When writing large files, consider streaming approaches to avoid loading all data into memory.

Prerequisites

Required

Optional

  • Optional: Apache Commons CSV or OpenCSV libraries
    Optional
  • Maven or Gradle for dependency management
    Optional

Keyboard Shortcuts

ActionShortcut
CopyCopy code blocks or text as neededCtrl+C
PastePaste into your editor or terminalCtrl+V

People Also Ask

What is the simplest way to write CSV in Java?

The simplest approach uses java.io with a small escaping helper. It works for tiny datasets but becomes unwieldy for complex data. For production use, consider a library like Apache Commons CSV or OpenCSV to handle escaping, quotes, and encoding automatically.

You can start with a basic Java IO example, but for robust CSV writing, libraries are recommended.

Should I always use a CSV library?

Not always. For quick experiments or tiny datasets, plain IO suffices. For real-world apps with many fields, special characters, or varied delimiters, a library reduces bugs related to escaping and encoding.

If in doubt, prefer a library for reliability.

How do I handle null values in CSV output?

Most CSV libraries allow you to configure null handling, often treating null as an empty field. If using plain IO, replace nulls with an empty string before writing.

Treat nulls as empty cells to keep the CSV well-formed.

Can I customize the delimiter or encoding?

Yes. Libraries expose CSVFormat or CSVWriter options to set a delimiter (e.g., ';') and encoding (e.g., UTF-8). Plain IO requires manual handling in the writer logic.

You can customize delimiter and encoding when using a library or with careful manual formatting.

Main Points

  • Use try-with-resources to manage IO safely
  • Escape fields containing delimiters or quotes
  • Libraries like Apache Commons CSV/OpenCSV simplify writing
  • Verify output with tests to catch edge cases

Related Articles