Introduction
If you have a situation where you need to write data to CSV file, one option should be using apache commons library. If you're using Maven, first you'll need to add dependency into pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
Get Gayle Laakmann - Cracking the Coding Interview - 4th, 5th and 6th edition
Code sample
Following code contains a solution for this issue:
package com.cloud.customers.utils; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; public class ExportDataToCsv { private static final String SAMPLE_CSV_FILE = "./sample.csv";
public void exportDataToCsv() throws IOException { BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("customerId", "locationId")); Map<String, String> data = new HashMap<String, String>(); for (Map.Entry<String, String> entry : data.entrySet()) { csvPrinter.printRecord(Arrays.asList(entry.getKey(), entry.getValue())); } csvPrinter.flush(); } }
You can find this code also on github.