【问题标题】:How to read csv file by using headers using java? [closed]java - 如何使用标头读取csv文件? [关闭]
【发布时间】:2014-01-15 06:06:44
【问题描述】:

我有一个 csv 文件,其中包含 5 个标头字段,例如 field1、field2、field3、field4、field5。 该文件包含不同用户的此标头的数据。 有些列可能包含空值,因为只有三列是强制性的。

我想通过指定标题来读取列,就像我指定 field1 和 field3 然后只读取这些列的值。

我尝试使用 opencsv 来执行此操作并读取 opencsv 的所有功能。 我也试过 CSVReader。

这是我的代码:

public void startScanFile(){
String mydemofile=pathtofile;
BufferedReader br =null;
try {
  System.out.println("\nEnter the column number that contains ip : ");
  br = new BufferedReader(new InputStreamReader(System.in));
  ipcolumn = Integer.parseInt(br.readLine());
      System.out.println("\nEnter the column number that contains username : ");
  br = new BufferedReader(new InputStreamReader(System.in));
  usercolumn = Integer.parseInt(br.readLine());
  System.out.println("\n Enter the column number that contains password");
  br = new BufferedReader(new InputStreamReader(System.in));
  passcolumn = Integer.parseInt(br.readLine());
    }catch(Exception e){
}
try {
    CSVReader csvReader = new CSVReader(new FileReader(mydemofile));
    String[] row;
    while ((row = csvReader.readNext())!=null){
    System.out.println("Col1 is is : " + row[1]);
    System.out.println("Col3 is : " + row[3]);
    System.out.println("Col4 is : " + row[4]);
}
} catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
} catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}

}

如何只读取指定标头的值?

【问题讨论】:

  • 到目前为止你得到了什么?或者至少向我们展示文件内容的示例
  • 请阅读this article
  • @RafaEl 我使用 opencsv api 及其函数 readAll 来读取 csv 并从结果中提取信息。

标签: java csv


【解决方案1】:

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      我可以推荐以下 csv 库。很好。检查下面的 url,其中包含如何使用 header 获取 csv 数据的示例,您还可以验证数据。

      http://supercsv.sourceforge.net/examples_reading.html
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-17
        • 2017-11-01
        • 2011-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 1970-01-01
        相关资源
        最近更新 更多