Site icon SpringHow

Using Java to write Data into CSV files

Creating and writing CSV files is easier than you think with Java. CSV stands for Comma Separated Values. As the name suggests, We just need to write values separated by a comma on each line to create such a file.

Identify the data you want to write as CSV

For example, You have an Array of Array that contains information about employees like this.

String[][] employees = {
                {"Man", "Sparkes", "msparkes0@springhow.com", "Engineering"},
                {"Dulcinea", "Terzi", "dterzi1@springhow.com", "Engineering"},
                {"Tamar", "Bedder", "tbedder2@springhow.com", "Legal"},
                {"Vance", "Scouller", "vscouller3@springhow.com", "Sales"},
                {"Gran", "Jagoe", "gjagoe4@springhow.com", "Business Development"}
};
Code language: Java (java)

In java, you can loop through these data and write the CSV file manually.

Create the CSV file using java.io.File class

In this step, you need to set up where the CSV file will go. For this, You need to define a File object and set up a write mechanism. For this example, we are going to use a file writer.

File csvFile = new File("employees.csv");
FileWriter fileWriter = new FileWriter(csvFile);Code language: Java (java)

The constructor for FileWriter will throw a java.io.IOException. You can either handle it using try-catch or add the exception to the method signature.

Java code to Write Data to CSV File

The next step is to add each record as comma-separated values in each line. For this, we can use a simple loop over java arrays. For example, we are using StringBuilder to create each line. And also, We are making sure to add commas and line breaks when necessary.

for (String[] data : employees) {
    StringBuilder line = new StringBuilder();
    for (int i = 0; i < data.length; i++) {
        line.append(data[i]);
        if (i != data.length - 1) {
            line.append(',');
        }
    }
    line.append("\n");
    fileWriter.write(line.toString());
}
fileWriter.close();Code language: Java (java)

You have almost completed your work to write data into CSV files using pure java. You can run this java program and see that it creates employees.csv file.

Problems with this approach

Even though this approach works for the data we created, there are certain rules you must follow to handle special characters in a CSV file.

  1. You should wrap a value with double quotes if it contains a comma(,). So it is usually better to wrap all values in the double quote(“).
  2. A string with a line break also needs to be wrapped in double-quotes. But some CSV readers may not recognize line breaks and will cause problems.
  3. In the case of wrapping with double quotes, you will need to escape double quotes within the string you are trying to quote. The escaping is done by adding another double quote.
    1. For example, Some Guy with a “Masters” Degree becomes “Some Guy with a “”Masters”” Degree“.

So let’s fix these problems in our program.

Final Java Program that writes CSV

Here is the final version of our CSV writer with all necessary fixes.

public class CSVWriter {
    public static void main(String[] args) throws IOException {
        String[][] employees = {
                {"Man", "Sparkes", "msparkes0@springhow.com", "Engineering"},
                {"Dulcinea", "Terzi", "dterzi1@springhow.com", "Engineering"},
                {"Tamar", "Bedder", "tbedder2@springhow.com", "Legal"},
                {"Vance", "Scouller", "vscouller3@springhow.com", "Sales"},
                {"Gran", "Jagoe", "gjagoe4@springhow.com", "Business Development"}
        };

        File csvFile = new File("employees.csv");
        FileWriter fileWriter = new FileWriter(csvFile);

        //write header line here if you need.

        for (String[] data : employees) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                line.append("\"");
                line.append(data[i].replaceAll("\"","\"\""));
                line.append("\"");
                if (i != data.length - 1) {
                    line.append(',');
                }
            }
            line.append("\n");
            fileWriter.write(line.toString());
        }
        fileWriter.close();
    }
}
Code language: Java (java)

Once we run this program, we can see that our employees.csv can be opened in applications like excel or google sheets.

Note that this program is just an example to demonstrate how we can create a simple CSV file using plain Java. Even though this approach is small and simple, I would advise you to use java libraries like apache commons-CSV library to write CSV files. You can find all these examples in our GitHub repository.

Exit mobile version