Selasa, 02 Desember 2014

Read and Parse a CSV file in java Tutorial with examples

A csv file is a simple text file containing text data, separated with a white space or a comma, to read a csv file in java we just need to read the file line by line and separate the values splitting by comma(',') or white-space(' ') accordingly.

Sample CSV file to read containing data separated by comma(',')

create a file in notepad with following data and save it as ProductQuantity.csv extension.
Product Code,Product Name,Quantity
BNP_BOND_1234,BNP Flexi Bond,50
FIS_MF_4567,FIS Super Saver Fund,110
BIRLA_MF_2789,BIRLA Mutual Fund,180
REL_BFWD_5678,REL Equity Bond,40

How to read and parse a csv file in Java

We have taken a sample csv file here that contains data separated by comma(','), we just need to read the file line by line and split the values by comma(',') to print values on console. Below is the java code to read values from csv file.
package com.tutorialsdesk.csv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadCSVFile {
public void readFile(String csvFileToRead) {
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] products = line.split(splitBy);
System.out.println("Products [Code= " + products[0] + " , Desc="+ products[1] +
" , Quantity=" + products[2] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String args[]){
String csvFileToRead = "D:/Assignment/ProductQuantity.csv";
ReadCSVFile reader = new ReadCSVFile();
reader.readFile(csvFileToRead);
}
}

Output

Below is the output of above program
Products [Code= Product Code , Desc=Product Name , Quantity=Quantity]
Products [Code= BNP_BOND_1234 , Desc=BNP Flexi Bond , Quantity=50]
Products [Code= FIS_MF_4567 , Desc=FIS Super Saver Fund , Quantity=110]
Products [Code= BIRLA_MF_2789 , Desc=BIRLA Mutual Fund , Quantity=180]
Products [Code= REL_BFWD_5678 , Desc=REL Equity Bond , Quantity=40]

NEXT READ Write to a CSV file in java.
Read and Parse a CSV file in java Tutorial with examples

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Source:http://www.tutorialsdesk.com/2014/10/read-and-parse-csv-file-in-java.html

Tidak ada komentar:

Posting Komentar