package com.csv; import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; public class ParseCSVInJava { /** * @param args */ public static void main(String[] args) { try { //csv file containing data String strFile = "D:\\WS12042011\\Parsing_XMLDOM_CSV_Text_In_Java\\src\\com\\csv\\Employee.csv"; //create BufferedReader to read csv file BufferedReader br = new BufferedReader( new FileReader(strFile)); String strLine = ""; StringTokenizer st = null; int lineNumber = 0, tokenNumber = 0; //read comma separated file line by line while( (strLine = br.readLine()) != null) { lineNumber++; //break comma separated line using "," st = new StringTokenizer(strLine, ","); while(st.hasMoreTokens()) { //display csv values tokenNumber++; System.out.println("Line:" + lineNumber +", Token:" + tokenNumber+ ", Value = "+ st.nextToken()); } //reset token number tokenNumber = 0; } } catch(Exception e) { System.out.println("Exception while reading csv file: " + e); } } }----------
out put
----------
Line:1, Token:1, Value = one:1
Line:1, Token:2, Value = two:2
Line:1, Token:3, Value = three:3
Line:1, Token:4, Value = four:4
Line:1, Token:5, Value = five:5
Line:1, Token:6, Value = six:6
Line:2, Token:1, Value = parsing
Line:2, Token:2, Value = comma
Line:2, Token:3, Value = separated
Line:2, Token:4, Value = file
Line:2, Token:5, Value = in
Line:2, Token:6, Value = java
No comments:
Post a Comment