What is a CSV file
CSV stands for Comma Separated Values. Thus each line of CSV file contains words that are separated with a comma (,).
A CSV file is different from a normal text file in that, a normal text file has a space as a separator while a CSV file has a comma as a separator. A CSV file is stored with a .csv extension.

Parse CSV file Java
Reading and parsing a csv file involves reading its contents line by line and processing each line. Processing might mean using its contents to do a task or just printing it to the console.
Since a csv file is a normal text file, it can be read in the same way as reading a text file in java.

In this article, we will look at how to parse ad read a csv file in java. In all the methods given ahead, we will be considering a sample csv file with following contents :

1,Antiseptic, Dr. Joseph Lister,England
2,Ballpoint Pen,John J. Loud,USA
3,Cement,Joseph Aspdin,England
4,Electric Battery,Volta,Italy
5,Electromagnet,William Sturgeon,England
6,Microphone,Alexander Graham Bell,USA
7,Oxygen,Antoine Laurent Lavoisier,France
8,Ozone, Christian Schonbein,Germany
9,Phosphorus,Hennig Brand,Germany

Method 1 : Using split function
Read the csv file line by line using readLine() method of  java.io.BufferedReader class. Split each line with comma(,) as a separator to get the words of the line into an array.
Now you can easily print the contents of the array by iterating over it or by using appropriate index.

static void processBySplit() { 
   BufferedReader reader = null; 
   try { 
      reader = new BufferedReader(new FileReader("d:\\discoveries.csv")); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
         String[] words = line.split(","); 
         System.out.println("[Discovery = \"" + words[0] + 
                "\", Discoverer = \"" + words[1] + "\", Country = \"" + 
                words[2] + "\"]"); 
      }
   } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
   } catch (IOException e) { 
      e.printStackTrace(); 
   } finally { 
      if (reader != null) { 
         try { 
           reader.close(); 
         } catch (IOException e) { 
           e.printStackTrace(); 
         }
       } 
   }
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”]
[Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”]
[Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”]
[Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”]
[Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”]
[Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”]
[Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”]
[Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”]
[Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

Method 2 : Using Regular Expression
This method is similar to the above method as it also utilizes split() method of java.lang.String class to extract words from the line.
But instead of directly splitting over a comma, a regular expression is used.The regular expression used is

“\\s*,\\s*”.

This expression can be divided into 3 parts :
“\\s*”, “,” and “\\s*”.
The expression “\\s*” matches zero or more spaces while a “,matches a comma which means that the complete expression matches a comma with zero or more spaces on its both sides.

Thus, split() method in the below code splits a String on the basis of a comma, which may or may not have space around it, and returns an array of words in a line which are separated by comma.

static void processByRegEx() { 
   BufferedReader reader = null; 
   try { 
      reader = new BufferedReader(new FileReader("d:\\discoveries.csv")); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
         String[] words = line.split("\\s*,\\s*"); 
         System.out.println("[Discovery = \"" + words[0] + 
              "\", Discoverer = \"" + words[1] + 
              "\", Country = \"" + words[2] + "\"]"); 
      } 
   } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
   } catch (IOException e) { 
      e.printStackTrace(); 
   } finally { 
      if (reader != null) { 
         try { 
           reader.close(); 
         } catch (IOException e) { 
           e.printStackTrace(); 
         } 
      }
   }
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”]
[Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”]
[Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”]
[Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”]
[Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”]
[Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”]
[Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”]
[Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”]
[Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

Method 3 : Using OpenCSV Library
Open csv is an open source library used to read a CSV file. Its main reader class is com.opencsv.Reader.

This class has a readAll() method which returns a list of String array. Each element of this list is a String array and represents a line of the file.
Thus, every element of the list is an array of the words of a line of file. If you want to read a file into an array list, then this method is the choice.

import com.opencsv.CSVReader; 
import java.io.IOException; 

static void processByOpenCsv() { 
   CSVReader reader = null; 
   try { 
     reader = new CSVReader(new FileReader("d:\\discoveries.csv")); 
     List<String[]> lines = reader.readAll(); 
     for (int i = 0; i < lines.size(); i++) { 
        String[] lineContents = lines.get(i); 
        System.out.println("[Discovery = \"" + lineContents[0] + 
              "\", Discoverer = \"" + lineContents[1] + 
              "\", Country = \"" + lineContents[2] + "\"]"); 
     }
   } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
   } catch (IOException e) { 
     e.printStackTrace(); 
   } finally { 
     if (reader != null) { 
       try { 
         reader.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”]
[Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”]
[Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”]
[Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”]
[Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”]
[Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”]
[Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”]
[Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”]
[Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

There is another way of reading a CSV file using com.opencsv.Reader class.
This class has an iterator() method which returns a java iterator over the lines of the file.
Thus, using iterator’s  hasNext() and next() method, a CSV file can be easily read.
Type of iterator is a String array and this its next() method also returns a String array containing the words of a line.

Thus, to read a file, iterate over the lines of the file

CSVReader reader = null; 
try { 
  reader = new CSVReader(new FileReader("d:\\discoveries.csv")); 
  Iterator<String[]> iterator = reader.iterator(); 
  while(iterator.hasNext()) { 
    String[] lineContents = iterator.next(); 
    System.out.println("[Discovery = \"" + lineContents[0] +
           "\", Discoverer = \"" + lineContents[1] + 
           "\", Country = \"" + lineContents[2] + "\"]");
   }
} catch (FileNotFoundException e) { 
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
} finally { 
   if (reader != null) { 
     try { 
       reader.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
}

Open csv library can be downloaded from the below link :

If you use Maven as a build tool then following dependency needs to be added in the build file:

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>3.8</version>
</dependency>

Click the clap if the article was useful.