Reputation: 77
Please help me to read the first column of the CSV file in Java. Here's my code:
public void fileload(String filename)throws IOException
{ int i=0;
//Sorter S= new Sorter();
File file=new File(filename); //Read File
Scanner inputfile = new Scanner(file);
while(inputfile.hasNext()) //Reading file content
{
orgarr[i]= inputfile.nextLine();
System.out.println(orgarr[i]);
i++;
}
Upvotes: 0
Views: 2147
Reputation: 41
Here I take the first column but I put a comma between the columns and when I fint that the number 10 is in the first column I print hello
File file = new File("src/test/resources/aaaa.csv");
List<String> lines = Files.readAllLines(file.toPath(),
StandardCharsets.UTF_8);
lines.stream().forEach(l -> {
String[] array = l.split(",", 2);
if(array[0].equals("10"))
System.out.println("Hello");
});
Upvotes: 0
Reputation: 44942
You can use commons-csv that would take care of reading the format e.g. assuming CSVFormat.DEFAULT
with optionally quoted text columns and comma as separator:
try (FileReader reader = new FileReader("your/path/to/file.csv")) {
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT);
parser.getRecords().stream()
.map(r -> r.get(0))
.forEach(System.out::println);
}
The best solution would depend on your file format and size. Above is probably not suitable for huge CSV files as it loads all the records into memory with getRecords()
.
Upvotes: 1