If you have a situation where you need to write data into the 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:


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()));

 You can find this code also on github.