0

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++;
    }
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Ali Asadullah Shah
  • 85
  • 1
  • 1
  • 12

2 Answers2

1

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().

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • I am reading a csv file with contents (2 columns only ): as "01L-900", "Ali" and have 107 records and task is to sort the first column contents – Ali Asadullah Shah Oct 21 '18 at 11:36
0

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");
        });