Java CSV Read Write by OpenCSV
This tutorial will cover CSV Read, Write operation by OpenCSV
How to complete this project?
-
It’s build by gradle, but You can download the library and use it
-
For use the version of 5.2, you need JDK version getter than 11
How to add OpenCS Gradle Dependency?
Please add the below dependency into your gradle build.gradle file
dependencies {
// ........
implementation group: 'com.opencsv', name: 'opencsv', version: '5.2'
// ........
}
Read CSV from file
- Example CSV
-
Create a file called country.csv with below data, or you can find it in project.
1, BD, Bangladesh
2, CA, Canada
3, AU, Australia
4, USA, USA
- Create below class
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSVFromFile {
public static void main(String[] args) {
CSVReader csvReader = null;
try {
csvReader = new CSVReader(new FileReader("country.csv"));
String[] line;
while ((line = csvReader.readNext()) != null) {
System.out.println("Country [id= " + line[0] + ", code= " + line[1] + " , name=" + line[2] + "]");
}
} catch (IOException | CsvValidationException e) {
e.printStackTrace();
}
}
}