1

I have the following code which reads the data from the csv file, it iterates over the rows but i don't manage to figure out how to iterate over specific columns (for example the first 2 columns of that row) in order to find the data. Any suggestions?

String file = "pathToCsvFile";
        BufferedReader reader = null;
        String line = "";
        try {
            reader = new BufferedReader(new FileReader(file));
            while((line = reader.readLine()) != null) {
                String[] row = line.split(",");
                for(String index:row) {
                    
                    //HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
                }
            }
        }
        catch(Exception e)  {
            e.printStackTrace();
        }
        finally {
            try {
                reader.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
      }
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Sanne112
  • 37
  • 4
  • Note that this is a very naive way to properly read a CSV. You're better off using a library if you want your code to be robust. For instance, a line containing `"hello, world","goodbye, world"` contains three commas, and yet there are just two columns here. Using `split` will cause this line to be parsed incorrectly. – MC Emperor Jul 11 '22 at 11:25

1 Answers1

0

I understand that "," is your delimiter so the key is in the algorithm :

    String file = "pathToCsvFile";
    BufferedReader reader = null;
    String line = "";
    try {
        reader = new BufferedReader(new FileReader(file));
        while((line = reader.readLine()) != null) {
            String[] row = line.split(",");
            for(int i = 0; i < row.length; i++) {
                
                //HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
                if(i < 2){
                     System.out.println(i+" -> "+row[i]);
                 }
            }
        }
    }
    catch(Exception e)  {
        e.printStackTrace();
    }
    finally {
        try {
            reader.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
  }
elgsylvain85
  • 421
  • 4
  • 10
  • Instead of the `if`, you are better off just rewrite your `for` loop: `for (int i = 0; i < 2; i++) { … }`. – MC Emperor Jul 11 '22 at 11:27
  • @MCEmperor, practical but a risk if the line is empty or contains less than two columns, that's why I loop expressly on the length of the columns.... "else break" then to complete my code – elgsylvain85 Jul 11 '22 at 15:15
  • So what is simple ? The logical code or your favorite function ? – elgsylvain85 Oct 04 '22 at 13:03