It looks like you are printing all the records on the same line .

Other methods like printRecords will be more helpful :

String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

csvFilePrinter.printRecords(excelParser.getRecords());


fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
Answer from Arnaud on Stack Overflow
Top answer
1 of 3
17

It looks like you are printing all the records on the same line .

Other methods like printRecords will be more helpful :

String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

csvFilePrinter.printRecords(excelParser.getRecords());


fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
2 of 3
11

Automatically close & flush

The Answer by Arnaud is correct and good. Here is a variation, shorter and more modern.

Here we:

  • Use the Path, File, and Files classes offered by modern Java NIO.2 to make easier work of file-handling.
  • Use a BufferedWriter for better performance with large amounts of data.
  • Specify the character encoding to be used. Usually UTF-8 is the best. If you do not understand, read this.
  • Include the necessary try-catches for file-related exceptions.
  • Add try-with-resources syntax to auto-close the file.
  • Skip the explicit flushing, as the buffered writer will be flushed automatically as part of auto-closing the BufferedWriter and CSVPrinter. To quote the Javadoc, calling java.io.Writer::close “Closes the stream, flushing it first.”.

Code:

CSVFormat format = CSVFormat.EXCEL.withHeader();
Path path = Paths.get( savePath + ".csv" );
try 
(
    BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
    CSVPrinter printer = new CSVPrinter( writer , format ) ;
)
{
    printer.printRecords( excelParser.getRecords() );
} 
catch ( IOException e )
{
    e.printStackTrace();
}
// At this point, the `CSVPrinter` is automatically closed. 
// And, ➡️ the `BufferedWriter` is automatically closed and flushed. 
🌐
Baeldung
baeldung.com › home › java › java io › introduction to apache commons csv
Introduction to Apache Commons CSV | Baeldung
January 8, 2024 - FileWriter out = new FileWriter("book_new.csv"); CSVPrinter printer = csvFormat.print(out); We presented the use of Apache’s Commons CSV library through a simple example.
🌐
CalliCoder
callicoder.com › java-read-write-csv-file-apache-commons-csv
Read / Write CSV files in Java using Apache Commons CSV | CalliCoder
February 18, 2022 - Reading or writing a CSV file is a very common use-case that Java developers encounter in their day-to-day work. If you need a simple way to read a CSV file or generate a new one for your project then this blog post is for you. In this post, You’ll learn how to read and write CSV files in Java using a very simple open source library called Apache Commons CSV.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
🌐
Medium
medium.com › javarevisited › boost-your-productivity-at-csv-files-with-apache-commons-csv-in-java-c52b33037c4c
Boost your Production at CSV files with Apache.commons.CSV in Java
July 18, 2020 - CSV (comma-separated values) files are used widely to exchange data between applications. However, operations with CSV files can be tricky and time-consuming. Apache Software Foundation gives us the Apache.Commons.CSV library that makes our life easier with CSV files READ/WRITE operations.
🌐
DZone
dzone.com › coding › java › working with csv files in java using apache commons csv
Working With CSV Files in Java Using Apache Commons CSV
April 30, 2018 - The Apache Commons CSV library is a Java library that can be used to read and write CSV files in a very simple and easy way.
🌐
Attacomsian
attacomsian.com › blog › read-write-csv-files-apache-commons-csv
How to read and write CSV files using Apache Commons CSV
September 24, 2022 - A step-by-step guide to reading and writing CSV files in Java using Apache Commons CSV library.
🌐
Javadevcentral
javadevcentral.com › write csv files using apache commons csv
Write CSV Files Using Apache Commons CSV | Java Developer Central
December 24, 2019 - As in the other post, the first step in writing CSV data is to first create a CSVFormat. To read data, we called the parse method on the CSVFormat. To write data, we can call one of the many available print methods.
🌐
GitHub
github.com › TransmissionZero › Apache-Commons-CSV-Example
GitHub - TransmissionZero/Apache-Commons-CSV-Example: An example of reading and writing CSV files using the Apache Commons CSV library. · GitHub
This is an example of reading and writing CSV files using the Apache Commons CSV library. The code takes a CSV file, then performs a find and replace operation for all matching values within a column of the CSV file. You will need Apache Maven and a Java JDK installed (the project was built and tested with the Java 8 LTS release on Windows and Linux, but it should be compatible with other JDK versions and OSes). To build the jar and the site documentation, run mvn clean verify site.
Author   TransmissionZero
Find elsewhere
🌐
SpringHow
springhow.com › 🏠 › java › apache commons csv to read and write csv files in java
Apache Commons CSV to Read and Write CSV files in Java | SpringHow
June 29, 2021 - To write this data into file, you just need to create CSVPrinter. And then you can simply start writing records(rows). If you want header row, then make sure you print them above all the data records.
🌐
GitHub
gist.github.com › 59b76f1bc60aecdf87cbcc88cd61a20f
Write to CSV file by Java using Apache Common Library https://goo.gl/yGQ4E2 · GitHub
Write to CSV file by Java using Apache Common Library https://goo.gl/yGQ4E2 - WriteCSVFileExample.java
🌐
Medium
medium.com › @kaveeshapiumini1999 › data-export-using-apache-commons-csv-09a154243d97
Data Export using Apache Commons CSV | by Kaveeshapiumini | Medium
January 4, 2024 - Within this method, Apache Commons CSV is used to create a CSV file writer and printer. Each Person object’s data is iterated through, and the CSVPrinter is used to write corresponding records to the CSV file.
🌐
Apache Commons
commons.apache.org › csv
Home – Apache Commons CSV
July 30, 2025 - Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-apache-commons-csv
Reading and Writing CSVs in Java with Apache Commons CSV
February 20, 2019 - The Apache Commons CSV library is the Apache Software Foundation's version of a Java CSV parser. According to the project summary, it attempts to "provide a simple interface for reading and writing CSV files of various types".
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › index.html
Overview (Apache Commons CSV 1.14.2-SNAPSHOT API)
Apache Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format. Common CSV formats are predefined in the CSVFormat class: Custom formats can be created using a fluent style API. Parsing files with Apache Commons CSV is relatively straight forward.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVPrinter.html
CSVPrinter (Apache Commons CSV 1.14.2-SNAPSHOT API)
Furthermore printRecords(Object...), printRecords(Iterable) and printRecords(ResultSet) methods can be used to print several records at once. Example: try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) { printer.printRecord("id", "userName", "firstName", "lastName", "birthday"); printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15)); printer.println(); printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29)); } catch (IOException ex) { ex.printStackTrace(); } This code will write the following to csv.txt: id,userName,firstName,lastName,birthday 1,john73,John,Doe,1973-09-15 2,mary,Mary,Meyer,1985-03-29 ·
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › apache › commons › csv
Write/Read CSV Files with Apache Commons CSV Example - Java Code Geeks
November 9, 2023 - So, Let’s see how we can write and read a simple CSV file using the Apache Commons CSV. The latest stable release of Commons CSV is 1.0, we can download it from here or we can pull it from the central Maven repositories using the following dependency in your project POM: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.0</version> </dependency> We create this simple POJO to contain the student data like id, firstName, lastName, gender and age.
🌐
Simplesolution
simplesolution.dev › java-write-read-csv-file-using-apache-commons-csv
Write and Read CSV File in Java using Apache Commons CSV
To download the Apache Commons CSV jar file you can visit Apache Commons CSV download page at commons.apache.org · import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; import java.io.IOException; public class WriteCsvFileExample { public static void main(String...
🌐
Blogger
albert-kuo.blogspot.com › 2017 › 06 › how-to-use-apache-commons-csv-to.html
albert's blog: How to use Apache Commons CSV to Read/Write CSV file
package albert.practice.csv; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import lombok.extern.slf4j.Slf4j; @Slf4j public class CSVTest { // Delimiter used in CSV file private static final String NEW_LINE_SEPARATOR = "\n"; // CSV file header private static final String[] FILE_HEADER = {"ns", "identifier"}; // OpcVo attri
Top answer
1 of 3
8

Use the APPEND option:

BufferedWriter writer = Files.newBufferedWriter(
        Paths.get(CSV_FILE), 
        StandardOpenOption.APPEND, 
        StandardOpenOption.CREATE);

You have to set things up so that one of the following is true:

  1. Before you begin, ensure the output file is empty or non-existent; OR
  2. Use the APPEND option only on the second and subsequent calls to generateCSV

BTW, you are creating a new BufferedWriter and CSVPrinter on each call to generateCSV, and not closing either one. This is wasteful, you should probably create those in the constructor, implement Closeable, and implement a close() method to clean up. Then wrap the calling code in a try-with-resources that instantiates generateCSV.

2 of 3
3

Here is one more easy way. After checking file existence only you should instantiate the Writer object else while instantiating file will get created and every time you will get file.exists() as true. If file exists you need to create CSVPrinter with withSkipHeaderRecord() else go with any implementation of header() method. FileWriter constructor takes appendable argument with File parameter. If file is there you have to make the appendable parameter as true.

File file = new File(filePath.concat("/").concat(fileName));
        if(file.exists()) {
            fileWriter = new FileWriter(file, true);
            csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withSkipHeaderRecord());
        }
        else {
            fileWriter = new FileWriter(file);
            csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader("FirstName", "LastName", "DOB"));
            
        }