How to Read CSV file in Java ?

CSV file means comma separated values. You can open and edit csv file in any text editor and also you can use MS Excel for the same.

We need to have one csv file that we are going read in this article. So check below article to know how to create CSV file in Java.

How to Create CSV file in Java ?

Here we will use BufferedReader with Automatic Resource Management to read CSV file. If you do not aware of these two in check below two articles.


How to Read file in Java ?
Automatic Resource Management in Java

Below is CSV file that we want to read in this article.

Read CSV File Using BufferedReader with Automatic Resource Management.

package com.infybuzz.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;

public class ReadCsvFile {

 public static void main(String[] args) {
  
  try (BufferedReader br = Files.newBufferedReader(Paths.get("D:\\hello.csv"))){
   
   String str = "";
   StringBuilder stringBuilder = new StringBuilder();
   
   //reading file line by line
   
   while((str = br.readLine()) != null){
    
    StringTokenizer tokenizer = new StringTokenizer(str, ","); // for csv file data comm(,) is delimeter
    
    while (tokenizer.hasMoreElements()) {
     
     System.out.println(tokenizer.nextElement());
     
    }
   }
   
   System.out.println(stringBuilder.toString());
   
  }catch (IOException ex) {
   ex.printStackTrace();
  }
 }

}

Output

Name
Website
Country
Raj
www.infybuzz.com
India
John
www.infybuzz.com
USA


0 Comments