forked from lokeshgupta1981/Core-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadCSV.java
More file actions
75 lines (59 loc) · 1.68 KB
/
ReadCSV.java
File metadata and controls
75 lines (59 loc) · 1.68 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.howtodoinjava.io;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class ReadCSV {
public static void main(String[] args) {
// 1. OpenCSV
try(CSVReader reader
= new CSVReader(new FileReader("SampleCSVFile.csv")))
{
String [] nextLine;
//Read one line at a time
while ((nextLine = reader.readNext()) != null)
{
//Use the tokens as required
System.out.println(Arrays.toString(nextLine));
}
}
catch (IOException | CsvValidationException e) {
e.printStackTrace();
}
//2 Scanner
//Get scanner instance
try(Scanner scanner = new Scanner(new File("SampleCSVFile.csv"))){
//Read line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Scan the line for tokens
try (Scanner rowScanner = new Scanner(line)) {
rowScanner.useDelimiter(",");
while (rowScanner.hasNext()) {
System.out.print(scanner.next());
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//3 Splitting
try(BufferedReader fileReader
= new BufferedReader(new FileReader("SampleCSVFile.csv")))
{
String line = "";
//Read the file line by line
while ((line = fileReader.readLine()) != null)
{
//Get all tokens available in line
String[] tokens = line.split(",");
//Verify tokens
System.out.println(Arrays.toString(tokens));
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}