csv-writing

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by separators (commas).

Note
Writing a CSV file is just like writing a normal text file, just beware of the “double-quotes” issue that mentions in my previous CSV parsing example.

In this tutorial, we will show you a simple CVSUtils class to write data or objects into a CVS file easily.

1. CSV Writing Example

1.1 Review the following CVSUtils class, it supports custom separator, custom enclose quote (default is empty), escaped the double-quotes with another double quote (RFC4180)

CSVUtils.java

package com.mkyong.utils;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class CSVUtils {

    private static final char DEFAULT_SEPARATOR = ',';
    
    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    //https://tools.ietf.org/html/rfc4180
    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());


    }

}

1.2 Example to show the CSVUtils usage.

CSVUtils.java

package com.mkyong.utils;

import java.io.FileWriter;
import java.util.Arrays;

public class CVSUtilExample {

    public static void main(String[] args) throws Exception {

        String csvFile = "/Users/mkyong/csv/abc.csv";
        FileWriter writer = new FileWriter(csvFile);

        CSVUtils.writeLine(writer, Arrays.asList("a", "b", "c", "d"));

        //custom separator + quote
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bb,b", "cc,c"), ',', '"');

        //custom separator + quote
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc,c"), '|', '\'');

        //double-quotes
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc\"c"));


        writer.flush();
        writer.close();

    }

}

Output

/Users/mkyong/csv/abc.csv
a,b,c,d
"aaa","bb,b","cc,c"
'aaa'|'bbb'|'cc,c'
aaa,bbb,cc""c

2. More Examples

Let review another example, it creates a List of objects, and write it to a CSV file.

2.1 A Developer class.

Developer.java

package com.mkyong.csv;

import java.math.BigDecimal;

public class Developer {

    private String name;
    private BigDecimal salary;
    private int age;

    public Developer(String name, BigDecimal salary, int age) {
        this.name = name;
        this.salary = salary;
        this.age = age;
    }

    //...
}

2.2 Example.

CVSUtilExample.java

package com.mkyong.utils;

import com.mkyong.java8.Developer;

import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CVSUtilExample {

    public static void main(String[] args) throws Exception {

        String csvFile = "/Users/mkyong/csv/developer.csv";
        FileWriter writer = new FileWriter(csvFile);

        List<Developer> developers = Arrays.asList(
                new Developer("mkyong", new BigDecimal(120500), 32),
                new Developer("zilap", new BigDecimal(150099), 5),
                new Developer("ultraman", new BigDecimal(99999), 99)
        );

        //for header
        CSVUtils.writeLine(writer, Arrays.asList("Name", "Salary", "Age"));
		
        for (Developer d : developers) {

            List<String> list = new ArrayList<>();
            list.add(d.getName());
            list.add(d.getSalary().toString());
            list.add(String.valueOf(d.getAge()));

            CSVUtils.writeLine(writer, list);

			//try custom separator and quote. 
			//CSVUtils.writeLine(writer, list, '|', '\"');
        }

        writer.flush();
        writer.close();

    }

}

Output

/Users/mkyong/csv/developer.csv
Name,Salary,Age
mkyong,120500,32
zilap,150099,5
ultraman,99999,99
Note
If you are still not comfortable to implement yourself, try this third party CSV library – OpenCSV.

Done.

References

  1. Ostermiller Java Utilities – Comma Separated Values (CSV)
  2. RFC4180 – Format for Comma-Separated Values (CSV)
  3. OpenCSV website
  4. How to parse a CSV file in Java
  5. Wikipedia – Comma-Separated Values (CSV)