0

我有以下代码从 csv 文件中读取数据,它遍历行,但我不知道如何遍历特定列(例如该行的前 2 列)以找到数据。有什么建议么?

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

1 回答 1

0

我知道“,”是您的分隔符,因此关键在于算法:

    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();
        }
  }
于 2022-01-04T23:36:47.070 回答