🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVPrinter.html
CSVPrinter (Apache Commons CSV 1.14.2-SNAPSHOT API)
org.apache.commons.csv.CSVPrinter · All Implemented Interfaces: Closeable, Flushable, AutoCloseable · public final class CSVPrinter extends Object implements Flushable, Closeable · Prints values in a CSV format. Values can be appended to the output by calling the print(Object) method.
🌐
GitHub
github.com › apache › commons-csv › blob › master › src › main › java › org › apache › commons › csv › CSVPrinter.java
commons-csv/src/main/java/org/apache/commons/csv/CSVPrinter.java at master · apache/commons-csv
* 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(); * } * </pre> * * <p>This code will write the following to csv.txt:</p> * <pre> * id,userName,firstName,lastName,birthday ·
Author   apache
🌐
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. You can read more about the library here. The code backing this article is available on GitHub.
🌐
Stack Overflow
stackoverflow.com › questions › 71378344 › csvprinter-java
csv - CSVPrinter java - Stack Overflow
As per the javadoc (https://commons.apache.org/proper/commons-csv/apidocs/index.html) DEFAULT is a CSVFormat instance with predefined builder in it. You can update the builder or create one from scratch. Here is a quick example : BufferedWriter successWriter = Files.newBufferedWriter(Paths.get( "C:\\temp\\testingtest.csv")); char delimiter = ';'; CSVPrinter csvPrinter = new CSVPrinter(successWriter, // Creates a new default builder.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVPrinter.java.html
CSVPrinter.java - Apache Commons
* </p> * * <p>Example:</p> * * <pre> * 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(); * } * </pre> * * <p>This code will write the following to csv.txt:</p> * <pre> * id,userName,firstName,lastName,birthday * 1,john73,John,Doe,1973-09-15 * * 2,mary,Mary,Meyer,1985-03-29 * </pre> */ public final class CSVPrinter implements Flushable, Closeable { /** The place that the values get written.
🌐
Java Tips
javatips.net › api › org.apache.commons.csv.csvprinter
Java Examples for org.apache.commons.csv.CSVPrinter
public static String loadCsv(String path) throws IOException { StringBuilder out = new StringBuilder(); CSVParser parse = org.apache.commons.csv.CSVParser.parse(new File(path), Charset.forName("utf-8"), CSVFormat.EXCEL); CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL); printer.printRecords(parse); printer.close(); String csv = out.toString().replaceAll("(?<!\r)\n", "\r"); return csv; }
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › src-html › org › apache › commons › csv › CSVPrinter.html
Source code - Apache Commons
057 * </p> 058 * 059 * <p>Example:</p> 060 * 061 * <pre> 062 * try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) { 063 * printer.printRecord("id", "userName", "firstName", "lastName", "birthday"); 064 * printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15)); 065 * printer.println(); 066 * printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29)); 067 * } catch (IOException ex) { 068 * ex.printStackTrace(); 069 * } 070 * </pre> 071 * 072 * <p>This code will write the following to csv.txt:</p> 073 * <pre> 074 * id,userName,firstName,lastName,birthday 075 * 1,john73,John,Doe,1973-09-15 076 * 077 * 2,mary,Mary,Meyer,1985-03-29 078 * </pre> 079 */ 080public final class CSVPrinter implements Flushable, Closeable { 081 082 /** The place that the values get written.
🌐
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 - import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; public class CSVWriter { private static final String SAMPLE_CSV_FILE = "./sample.csv"; public static void main(String[] args) throws IOException { try ( BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Name", "Designation", "Company")); ) { csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google"); csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft"); csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple"); csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook")); csvPrinter.flush(); } } }
🌐
Program Creek
programcreek.com › java-api-examples
org.apache.commons.csv.CSVPrinter Java Examples
private void mappingIdsInMetadata(String mappedMetadataFile) throws Exception { // read mappings file FileInputStream fis = new FileInputStream(this.dataDirectory + File.separator + this.metadataFile + ".id-map"); ObjectInputStream ois = new ObjectInputStream(fis); HashMap<Integer, ArrayList<Integer>> documentIdMapping = (HashMap<Integer, ArrayList<Integer>>) ois .readObject(); ois.close(); // open metadata file, replace ids, write to temporary metadata file BufferedWriter writer = new BufferedWriter(new FileWriter(mappedMetadataFile)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.
Find elsewhere
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. 
🌐
Java2s
java2s.com › example › java-api › org › apache › commons › csv › csvprinter › println-0-0.html
Example usage for org.apache.commons.csv CSVPrinter println
/** * Prints table to output string as CSV/*from w w w .j a v a2s.c o m*/ * * @param out output * @param <T> value type * @param table table * @throws IOException */ public static <T> String tableToCsv(Table<String, String, Boolean> table) throws IOException { StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); List<String> firstRow = new ArrayList<>(); firstRow.add(" "); firstRow.addAll(table.columnKeySet()); printer.printRecord(firstRow); for (String rowKey : table.rowKeySet()) { printer.print(rowKey); for (String columnKey : table.columnKeySet()) { printer.print(table.get(rowKey, columnKey)); } printer.println(); } printer.close(); return sw.toString(); }
🌐
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-csv-with-java
Parse and Generate CSV with Java | Parse and Generate Formats
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.List; public class CsvWriterExample { public static void main(String[] args) throws IOException { List<String> headers = Arrays.asList("ID", "Product", "Price"); List<List<String>> records = Arrays.asList( Arrays.asList("1", "Laptop", "1200.50"), Arrays.asList("2", "Keyboard", "75.00") ); try (Writer writer = new FileWriter("output.csv"); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(headers.toArray(new String[0])))) { for (List<String> record : records) { csvPrinter.printRecord(record); } } } }
🌐
Javadevcentral
javadevcentral.com › write csv files using apache commons csv
Write CSV Files Using Apache Commons CSV | Java Developer Central
December 24, 2019 - After creating a CSVFormat with default properties (comma as delimiter), we call the print method passing the created buffered writer. This returns a CSVPrinter. A BufferedWriter extends Writer which is an Appendable.
🌐
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 - import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; public class BasicCsvWriter { public static void main(String[] args) { try { //We have to create the CSVPrinter class object Writer writer = Files.newBufferedWriter(Paths.get("student.csv")); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Student Name", "Fees")); //Writing records in the generated CSV file csvPrinter.printRecord("Akshay Sharma", 1000); csvPrinter.printRecord("Rahul Gupta", 2000); csvPrinter.printRecord("Jay Karn", 3000); //Writing records in the form of a list csvPrinter.printRecord(Arrays.asList("Dev Bhatia", 4000)); csvPrinter.flush(); } catch (IOException e) { e.printStackTrace(); } } }
🌐
Dukelearntoprogram
dukelearntoprogram.com › course2 › doc › javadoc › org › apache › commons › csv › CSVPrinter.html
CSVPrinter
org.apache.commons.csv.CSVPrinter · All Implemented Interfaces: java.io.Closeable, java.io.Flushable, java.lang.AutoCloseable · public final class CSVPrinter extends java.lang.Object implements java.io.Flushable, java.io.Closeable · Prints values in a CSV format.
🌐
GitHub
github.com › apache › commons-csv › blob › master › src › test › java › org › apache › commons › csv › CSVPrinterTest.java
commons-csv/src/test/java/org/apache/commons/csv/CSVPrinterTest.java at master · apache/commons-csv
try (Reader reader = new FileReader("src/test/resources/org/apache/commons/csv/CSV-259/sample.txt"); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) {
Author   apache
🌐
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 - However, there are some useful ... from a JDBC ResultSet object. The CSVPrinter class implements the Flushable and Closeable interfaces, making its behavior similar to an extension of a usual Java Writer or StringWriter....
🌐
Apache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
The User Guide migrated to the Javadoc · Copyright © 2005-2025 The Apache Software Foundation. All Rights Reserved
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"));
            
        }