Search code examples
javaiterationcsvreader

How to read a specific column of a row from a csv file in java


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

Solution

  • 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();
            }
      }