Working with CSV file
CSV stands for Comma separated Value.
CSV file is a normal text file,with .csv extension
It contains values separated by , or any other delimiter.
CSV file is a normal text file,with .csv extension
It contains values separated by , or any other delimiter.
CSV file is another commonly used file in Java.Lets see how to parse the csv file,to read the data
data.csv
1001,satya,5000.00 1002,Raja,6000.00 1003,Rani,7000.00
CSVDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.util.StringTokenizer;public class CSVDemo { public static void main(String[] args)throws Exception { FileReader fileReader = new FileReader("data.csv"); BufferedReader bufRdr = new BufferedReader(fileReader); String line = null; int row = 1; //read each line of text file while((line = bufRdr.readLine()) != null) { StringTokenizer st = new StringTokenizer(line,","); System.out.print("Row "+ row+": "); while (st.hasMoreTokens()) {//for each line,it loops for 3 times.nextToken() gives each element System.out.print(st.nextToken()+" "); } System.out.println();//print empty line row++; } }} |
Output:-
Row 1: 1001 satya 5000.00
Row 2: 1002 Raja 6000.00
Row 3: 1003 Rani 7000.00
Explaination:-
1.Use FileReader object to point to your csv file for reading. The csv file can have any extension,but .csv is recommended
2.Use BufferedReader concept so that u can store the file content in a temporary buffer,and read the file line by line
3.Read the file,line by line using bufferReader.readLine()
4.For each line
Take stringTokenizer to separate the line content.Here we have used delimiter(,).You can also use other delimiter like *,space…
For each tokenizer,use hasMoreTokens() to iterate through all words present in a line.
st.nextToken() will give you next token(word)
Hope this will help you.
Thank you for reading this article.
Any Bug/Suggestion,We would like to hear from you.
No comments:
Post a Comment