How to read a CSV file via Java

In this blog post, I will be covering how you can read a CSV file via Java.

What is a CSV file?

CSV stands for Comma Separated Values.  The fields in a CSV file are separated by commas.  So for example, a CSV file will be seen in Notepad as follows:

 

However, if you open the same CSV file in Excel and will be seen as follows:

 

A CSV file is used to store tabular data. You can open a CSV file in Microsoft Excel.

Code to read CSV file

Consider the following code sample:

package learnjava.io;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class ReadCSVDemo {public static void main(String[] args) {String fileName="F:/Test.csv";try {BufferedReader br = new BufferedReader(new FileReader(fileName));String str = br.readLine();while(str != null){String[] contents = str.split(",");for(String cell:contents){System.out.print(cell);}str = br.readLine();System.out.println();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

 

First, the input file is read line by line using a BufferedReader. Each line is split using the String,split method and its contents are printed.

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set