Java - Write CSV File with Apache.commons.csv
Have you tried flushing and closing the CSVPrinter, not the FileWriter?
The Answer by Arnaud is correct and good. Here is a variation, shorter and more modern.
Here we:
- Use the
Path
,File
, andFiles
classes offered by modern Java 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
andCSVPrinter
. To quote the Javadoc, callingjava.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();
}
Edit: There was a bracket missing.
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();