Java - Writing to CSV File

CSV stands for Comma Separated Values.

A CSV file is a normal plain text file that stores data in columns, with a separator (by default comma) between the columns.

In this tutorial, let's learn how to handle CSV files in a Java Spring Boot application.

OpenCSV Library

The OpenCSV is one of the commonly used CSV parser libraries available for Java.

In order to use OpenCSV library, the application needs Java 7 or above.

Add OpenCSV Library to a Java Project

For maven projects, add the below dependency in pom.xml file.

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.1</version>
</dependency>

For gradle projects, add the below dependency.

compile group: 'com.opencsv', name: 'opencsv', version: '4.1'

Or, download the JAR file and include it in the project class path.

Download OpenCSV JAR

Writing to a CSV file

To write content to a CSV file, we need to create an instance of CSVWriter by providing FileWriter object as shown below.

  • Before writing data, create an instance of CSVWriter by providing FileWriter object as shown below.
  • Use the method writeNext() to write data line by line.
  • Use the method writeAll() to write data all the lines at once.
  • After writing data, we need to close the CSVWriter using close() method.
  • By default, the column separator is comma, which can be changed while configuring CSVWriter.

NOTE: If the CSV file doesn't exist at the path specified, then the file is created, otherwise the content of the existing file is updated.

Sample Data

Let's asume the below data in the CSV file, where the separator is comma (the default separator).

ID,Name,Class,Marks
1,Arun,10,520
2,Sravan,10,630
3,Kiran,10,580

1. Writing to a CSV file line by line

public static void writeDataLineByLine() {
    // specifying the CSV file path
    String filePath = "/files/sample.csv";

    // creating File object with the file location specified
    File file = new File(filePath);

    try {
        // creating FileWriter object with file as parameter
        FileWriter fileWriter = new FileWriter(file);

        // creating CSVWriter object using FileWriter object
        CSVWriter csvWriter = new CSVWriter(fileWriter);

        // writing header to CSV file
        csvWriter.writeNext(new String[] { "ID", "Name", "Class", "Marks" });

        // writing data to CSV file
        csvWriter.writeNext(new String[] { "1", "Arun", "10", "520" });
        csvWriter.writeNext(new String[] { "2", "Sravan", "10", "630" });
        csvWriter.writeNext(new String[] { "3", "Kiran", "10", "580" });

        // closing writer connection
        csvWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The generated CSV file contains the below data.

ID,Name,Class,Marks
1,Arun,10,520
2,Sravan,10,630
3,Kiran,10,580

2. Writing to a CSV file all lines at once

public static void writeDataAllLinesAtOnce() {
    // specifying the CSV file path
    String filePath = "/files/sample.csv";

    // creating File object with the file location specified
    File file = new File(filePath);

    try {
        // creating FileWriter object with file as parameter
        FileWriter fileWriter = new FileWriter(file);

        // creating CSVWriter object using FileWriter object
        CSVWriter csvWriter = new CSVWriter(fileWriter);

        // creating the list (containing both header and data) using String array
        List<String[]> data = new ArrayList<String[]>();
        data.add(new String[] { "ID", "Name", "Class", "Marks" });
        data.add(new String[] { "1", "Arun", "10", "520" });
        data.add(new String[] { "2", "Sravan", "10", "580" });
        data.add(new String[] { "3", "Kiran", "10", "580" });

        // writing data to CSV file
        csvWriter.writeAll(data);

        // closing writer connection
        csvWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The generated CSV file contains the below data.

ID,Name,Class,Marks
1,Arun,10,520
2,Sravan,10,630
3,Kiran,10,580

3. Writing to a CSV file with a custom separator

By default, the separator is comma (,) which can be changed by providing the custom separator as a parameter to CSVWriter constructor as shown below.

Here is the syntax of the constructor to be used.

// Constructs CSVWriter with the supplied separator, quote character, escape character, and line ending string
CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd);

Here is the implementation using the above construct.

// creating FileWriter object with file as parameter
FileWriter fileWriter = new FileWriter(file);

// creating CSVWriter object using FileWriter object
CSVWriter csvWriter = new CSVWriter(fileWriter, '|',
                               CSVWriter.NO_QUOTE_CHARACTER,
                               CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                               CSVWriter.DEFAULT_LINE_END);

The generated CSV file contains the below data.

ID|Name|Class|Marks
1|Arun|10|520
2|Sravan|10|630
3|Kiran|10|580

Conclusion

Now, we know how to write data to a CSV file in a Spring Boot application using the opencsv library.

Related Links

  • Writing data to a CSV file
  • Reading data from a CSV file
  • Mapping data from a CSV file to Java beans
  • Mapping data from Java beans to a CSV file

References

For more details about the OpenCSV library, refer the official documentation in the below links.