How to Read CSV Files in Java?
Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into and exported from programs like Microsoft Excel and Microsoft Office that store data in tables. A delimiter identified and separated different data tokens in a CSV file.We use the CSV file format when we move tabular data between programs that natively operate on incompatible formats. In Java, you can read CSV files in the following ways. A comma (,) serves as a CSV file's default separator.
There are the following ways of printing an exhibit in Java:
Using the OpenCSV API and the Java Scanner class's String.split() method
- Java Scanner class
- Java String.split() method
- Using OpenCSV API
A CSV (Comma-Separated Values) file is similar to a regular plain text file in that it stores data by columns and uses a delimiter (usually a comma ",")
OpenCSV is a Java library for parsing CSV files. OpenCSV allows you to performthe basic CSV operations you need. OpenCSV currently only supports Java 7 as the minimum supported version. Use OpenCSV to process CSV files in Java, as the Java programming language does not have native support for efficiently processing CSV files.
The CSV file can be read in two ways:
- Line by line, read the data: Let's examine each CSV file line one at a time. Bypassing the filereader object of the CSV file, we must first construct and initialize the CSVReader object before we can read data line by line.After that, we must use the CSVReader object's readNext() method to read the data line by line, as shown in the code below.
// Java code to illustrate reading a
// CSV file line by line
public static void readDataLineByLine(String file)
{
try {
// Create an object of filereader
// class with CSV file as a parameter.
FileReaderfilereader = new FileReader(file);
// create csvReader object passing
// file reader as a parameter
CSVReadercsvReader = new CSVReader(filereader);
String[] nextRecord;
// we are going to read data line by line
while ((nextRecord = csvReader.readNext()) != null) {
for (String cell :nextRecord) {
System.out.print(cell + "\t");
}
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
- Immediately read all data: ThereadNext() method is used to read the CSV records one at a time.Additionally, CSVReader provides a readAll() method for simultaneously reading all records into a List.
List allData = csvReader.readAll();
As can be seen in the codes' output, when we read a csv file by default, the header is not ignored.When creating CSVReader, we can specify a start line to skip the first item in the list.
CSVReadercsvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
// Java code to illustrate reading a
public static void readAllDataAtOnce(String file) {
try {
// Create an object of file reader
// class with CSV file as a parameter.
FileReaderfilereader = new FileReader(file);
// create csvReader object and skip first Line
CSVReadercsvReader = new CSVReaderBuilder(filereader)
.withSkipLines(1)
.build();
List<String[]>allData = csvReader.readAll();
// print Data
for (String[] row : allData) {
for (String cell : row) {
System.out.print(cell + "\t"); }
System.out.println();} }
catch (Exception e) {
e.printStackTrace();
} }
Reading a CSV file with a different separator a delimiter other than a comma, such as a pipe, semicolon, or other character, can be used to separate CSV files. The following example demonstrates how to read CSV file data separated by a semicolon.
Example of a CSV file separated by semicolons:
/ Java code to illustrate
// Reading CSV File with different separator
public static void readDataFromCustomSeparator(String file) {
try {
// Create an object of file reader class with a CSV file as a parameter.
FileReaderfilereader = new FileReader(file);
// create a csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReadercsvReader = new CSVReaderBuilder(filereader)
.withCSVParser(parser)
.build();
// Read all data at once
List<String[]>allData = csvReader.readAll();
// Print Data.
for (String[] row : allData) {
for (String cell : row) {
System.out.print(cell + "\t");}
System.out.println(); } }
catch (Exception e) {
e.printStackTrace();
} }