How to Read CSV Files in Java?

The CSV stands for Comma-Separated Values. It is a simple file format that is used to store tabular data in simple text form, such as a spreadsheet or database. The files in the CSV format can be imported to and exported from programs (Microsoft Office and Excel) that store data in tables. The CSV file used a delimiter to identify and separate different data tokens in a file. The CSV file format is used when we move tabular data between programs that natively operate on incompatible formats. The default separator of a CSV file is a comma (,).

Use of CSV File

CSV files are frequently used to transfer data across various software programs, such as database management systems, spreadsheet programs like Microsoft Excel, and programming languages. They offer a simple method for representing structured data in a format that is legible by humans.

Delimiter

CSV files include a variety of delimiters, including semicolons (;), tabs (\t), and pipes (|). The default separator is a comma (,). This adaptability helps prevent conflicts with data that might contain commas and supports various data formats.

There are following ways to print an array in Java:

  • Java Scanner class
  • Java String.split() method
  • Using OpenCSV API

How to create a CSV File?

There are two ways to create a CSV file:

  • Using Microsoft Excel
  • Using Notepad

Using Microsoft Excel

Microsoft Excel is a popular spreadsheet program that allows users to create and manipulate data in tabular form easily. Here's how to create a CSV file using Excel:

Step 1: Open Excel: Launch Microsoft Excel on your computer.

Step 2: Write the following data into the file:

How To Read CSV File in Java

Step 3: Now, save the file. Provide the file name CSVDemo and select CSV (Comma delimited) from the save as type menu. Now, click on the Save button.

How To Read CSV File in Java

Using Notepad

Step 1: Open notepad.

Step 2: Write some data into file separated by comma (,). For example:

Vivek, Singh, 23, 9999999, Chandigarh

Step 3: Save the file with .csv extension.

We have created the following file.

How To Read CSV File in Java

Java Scanner class

Java Scanner class provide various methods by which we can read CSV file. The Scanner class provides a constructor that produces values scanned from the specified file. It breaks data into the token form. It uses a delimiter pattern which by default matches white space. The resulting tokens then converted into values of different types using the next() methods.

To read a CSV file using the Scanner class, we first need to create an instance of Scanner and pass the file object as a parameter to its constructor. By default, Scanner uses whitespace as the delimiter, but we can specify a custom delimiter pattern to handle CSV files.

Example

Output:

Shashank, Mishra, Auditor, 909090090, 45000, Moti Vihar
Naveen, Singh, Accountant, 213344455, 12000, Shastri Nagar
Mahesh, Nigam, Sr. Manager, 787878878, 30000, Ashok Nagar
Manish, Gupta, Manager, 999988765, 20000, Saket Nagar

Explanation:

Using a Scanner object, the given Java code reads a CSV (Comma Separated Values) file called "demo.csv". It makes use of the useDelimiter() method to set the delimiter pattern to comma (,). Next, it uses a while loop to crawl over the contents of the file, using hasNext() to see if there are any more tokens available and next() to output each token. In order to free up system resources, it shuts the Scanner object at the end.

Java String.split() Method

Java String.split() identifies the delimiter and splits the rows into tokens.

The split() method in Java is a part of the String class, and it is used to split a string into an array of substrings based on a specified delimiter. Here's an explanation of how it works:

Syntax

The method parses a delimiting regular expression. The method returns an array of strings computed by splitting this string around matches of the given regular expression.

Parameters

regex: This is the regular expression that defines the delimiter pattern. The string will be split around matches of this regular expression.

Return Value

An array of strings is computed by splitting the original string around matches of the given regular expression.

ReadCSVExample2.java

Output:

Employee [First Name= Shashank, Last Name= Mishra, Designation= Auditor, 
Contact= 909090090, Salary= 45000, City= Moti Vihar]
Employee [First Name= Naveen, Last Name=Singh, Designation= Accountant, 
Contact=213344455, Salary= 12000, City= Shastri Nagar]
Employee [First Name= Mahesh, Last Name=Nigam, Designation= Sr. Manager, 
Contact=787878878, Salary= 30000, City= Ashok Nagar]
Employee [First Name= Manish, Last Name=Gupta, Designation= Manager, 
Contact=999988765, Salary= 20000, City= Saket Nagar]

Explanation

This Java code iterates through each line of data it reads from a CSV file called "demo.csv" using a BufferedReader. It represents personnel details by splitting each line into independent values based on commas. It outputs the parsed values, including first and last names, designations, contacts, salaries, and cities, in a prepared string for each line. To capture and publish any IOExceptions that might arise when reading a file, exception handling is developed.

Using OpenCSV API

OpenCSV is a third party API which provide standard libraries to read various versions of CSV file. The library provides better control to handle the CSV file. The library can also read TDF (Tab-Delimited File) file format.

Features of OpenCSV API

  1. Variable Number of Values per Line: CSV files containing a variable number of values per line can be handled by OpenCSV.
  2. Handling of Quoted Elements: It ensures accurate parsing by intelligently ignoring commas in quoted elements.
  3. Multi-Line Entries: OpenCSV enables the parsing of increasingly complicated data structures by supporting entries that span many lines.

The CSVReader class is used to read a CSV file. The class provides CSVReader class constructor to parse a CSV file.

Syntax

Parameters

reader: The reader to a CSV source.

separator: It is a delimiter which is used for separating entries.

Steps to read CSV file in eclipse:

Step 1: Create a class file with the name ReadCSVExample3 and write the following code.

Step 2: Create a lib folder in the project.

Step 3: Download opecsv-3.8.jar from

https://repo1.maven.org/maven2/com/opencsv/opencsv/3.8/opencsv-3.8.jar

Step 4: Copy the opencsv-3.8.jar and paste into the lib folder.

Step 5: Now, run the program.

ReadCSVExample3.java

Output:

Shashank Mishra Auditor 909090090 45000 Moti Vihar
Naveen Singh Accountant 213344455 12000 Shastri Nagar
Mahesh NigamSr. Manager 787878878 30000 Ashok Nagar
Manish Gupta Manager 999988765 20000 Saket Nagar

Explanation

This Java code uses the built-in Java IO classes to read data from a CSV file called "demo.csv". It sets up variables to hold the path to the file, the delimiter, and each line of the file. It generates a BufferedReader to read the file and iterates through each line, breaking it into tokens with a comma as the delimiter inside a try-with-resources block. After printing each token, it advances to the following line. In order to handle any IO exceptions that can arise while reading a file, exception handling is implemented. If an exception arises, the stack trace is printed.

ReadCSVExample4.java

Output:

Shashank; Mishra; Auditor; 909090090; 45000; Moti Vihar		
Naveen; Singh; Accountant; 213344455; 12000; Shastri Nagar		
Mahesh; Nigam; Sr. Manager; 787878878; 30000; Ashok Nagar		
Manish; Gupta; Manager; 999988765; 20000; Saket Nagar	

Conclusion

Finally, there are other ways to read CSV files in Java. These include using the built-in Java IO classes BufferedReader and FileReader, tokenizing the file with String.split(), or using the Scanner class with custom delimiter patterns. Furthermore, third-party libraries such as OpenCSV provide sophisticated functionality to manage CSV processing assignments. A number of variables, including the complexity of the file, the needed performance, and the intended functionality, influence the method selected.


Next TopicJava Tutorial