🏠JavaUsing Java to write Data into CSV files

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", "[email protected]", "Engineering"},
                {"Dulcinea", "Terzi", "[email protected]", "Engineering"},
                {"Tamar", "Bedder", "[email protected]", "Legal"},
                {"Vance", "Scouller", "[email protected]", "Sales"},
                {"Gran", "Jagoe", "[email protected]", "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", "[email protected]", "Engineering"},
                {"Dulcinea", "Terzi", "[email protected]", "Engineering"},
                {"Tamar", "Bedder", "[email protected]", "Legal"},
                {"Vance", "Scouller", "[email protected]", "Sales"},
                {"Gran", "Jagoe", "[email protected]", "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.

CSV file created from Java program

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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

3 Comments

    1. You are better off using apache-commons-csv to write CSV files as shown in https://springhow.com/apache-commons-csv/.

      But if you insist on doing it in a pure java way, You just need to add an array at the top of the list of arrays with headers.

      So
      String[][] employees = {
      {"Man", "Sparkes", "[email protected]", "Engineering"},
      {"Dulcinea", "Terzi", "[email protected]", "Engineering"},
      {"Tamar", "Bedder", "[email protected]", "Legal"},
      {"Vance", "Scouller", "[email protected]", "Sales"},
      {"Gran", "Jagoe", "[email protected]", "Business Development"}
      };

      becomes


      String[][] employees = {
      {"FIRST_NAME", "LAST_NAME", "EMAIL", "DEPARTMENT"}, //This is header
      {"Man", "Sparkes", "[email protected]", "Engineering"},
      {"Dulcinea", "Terzi", "[email protected]", "Engineering"},
      {"Tamar", "Bedder", "[email protected]", "Legal"},
      {"Vance", "Scouller", "[email protected]", "Sales"},
      {"Gran", "Jagoe", "[email protected]", "Business Development"}
      };

      or you could simply use the same block in the loop with the headers.

  1. Thanks for this code. I was searching long and hard on how to create and write data to csv files without using OpenCSV or any other packages. I have to put the data into a hashmap and therefore, facing difficulties.