Java - How to read and write CSV file with OpenCsv

When reading or writing CSV files in Java, you can use a library called OpenCsv. Of course, if you create a simple CSV file, you can implement it yourself.

Since I was only going to create a simple CSV file, I only implemented a read/write method. If you go to the site and look at the examples, we will guide you through creating efficient CSV files in an advanced way.

If you want to use the advanced features of OpenCsv, it would be good to refer to OpenCsv.

library settings

I have created a project with Gradle. If you use gradle, you can set the dependency as follows.

dependencies {
    ...
    implementation group: 'com.opencsv', name: 'opencsv', version: '4.4'
}

Write CSV

The following example creates a CSV file.

package example;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class OpenCsv {

    public static void writeDataToCsv(String filePath) throws IOException {
        CSVWriter writer = new CSVWriter(new FileWriter(filePath));
        String[] entries = "EW#City#State".split("#");  // 1
        writer.writeNext(entries);  // 2

        String[] entries1 = {"W", "Youngstown", "OH"};  // 3
        writer.writeNext(entries1);

        String[] entries2 = {"W", "Williamson", "WV"};
        writer.writeNext(entries2);

        writer.close();
    }

    public static void main(String args[]) throws IOException {
        writeDataToCsv("./sample.csv");
    }
}
  1. You can create an array of strings using split().
  2. When writeNext() is called, the argument is saved in the CSV file.
  3. You can also directly put items into the array.

The contents of the generated file are as follows.

"EW","City","State"
"W","Youngstown","OH"
"W","Williamson","WV"

Read CSV

The following is an example of creating a CSV file, reading the CSV file, and outputting data.

package example;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class OpenCsv {

    public static void writeDataToCsv(String filePath) throws IOException {
        CSVWriter writer = new CSVWriter(new FileWriter(filePath));
        String[] entries = "EW#City#State".split("#");  // 1
        writer.writeNext(entries);

        String[] entries1 = {"W", "Youngstown", "OH"};  // 2
        writer.writeNext(entries1);

        String[] entries2 = {"W", "Williamson", "WV"};
        writer.writeNext(entries2);

        writer.close();
    }

    public static void readDataFromCsv(String filePath) throws IOException {
        CSVReader reader = new CSVReader(new FileReader(filePath)); // 1
        String [] nextLine;
        while ((nextLine = reader.readNext()) != null) {   // 2
            for (int i = 0; i < nextLine.length; i++) {
                System.out.println(i + " " + nextLine[i]);
            }
            System.out.println();
        }
    }


    public static void main(String args[]) throws IOException {
        writeDataToCsv("./sample.csv");
        readDataFromCsv("./sample.csv");
    }
}
  1. Create a CSVReader.
  2. You can read the CSV file line by line with readNext(). An array is returned as many as the number of items.

The execution result is as follows.

0 EW
1 City
2 State

0 W
1 Youngstown
2 OH

0 W
1 Williamson
2 WV

Reference

codechachaCopyright ©2019 codechacha