【问题标题】:How to not read the header row while reading csv using Scanner? [duplicate]使用扫描仪读取 csv 时如何不读取标题行? [复制]
【发布时间】:2014-10-18 23:52:35
【问题描述】:

我需要读取一个 csv 文件才能使用 java 对其进行一些计算。我正在使用 Scanner 读取它,但我想在第一行之后(即标题行之后)开始读取它,现在我只是在做:while(inputStream.hasNext()) 读取所有内容,什么我应该这样做以不占用标题行吗?

【问题讨论】:

  • 只获取第一行,然后忽略它。在循环之外执行此操作,它应该可以工作。
  • 既然是 CSV,为什么不使用 OpenCSV 为例呢?

标签: java csv file-io


【解决方案1】:

您可以在不使用返回值的读取循环之外做一个额外的scan.nextLine();

Scanner scan = new Scanner(new File("C:\\input.txt"));
if (scan.hasNext()) {
    // skip header line
    scan.nextLine();
}

// write contents to output file
FileWriter fw = new FileWriter("C:\\output.txt");

// read the rest of the file
while (scan.hasNext()) {
    fw.write(scan.nextLine() + System.getProperty("line.separator"));
}

scan.close();
fw.close();

编辑:添加了将非标题内容写入输出文件的代码。如果您愿意,请随时在您的 scanfw 引用上添加一些 null 检查。

【讨论】:

  • 嗨,非常感谢!另外,您能告诉我如何不打印输出,而是将其写入另一个文件,例如 output.csv?
  • 我的意思是,就像我必须从列中找到最小值、最大值、平均值,并将其作为不同的列写入 output.csv,其中 Min、Max、Average 作为这些列的标题名称列。该怎么做?
  • 现在,如果我喜欢: fw.write(min + System.getProperty(",")); fw.write(max + System.getProperty(","));在 while 循环之后,我在 output.csv 文件中得到以下内容:0.03null0.26null(0.03 是最小值,0.26 是最大值)
  • 如果您的字符串中只需要一个逗号,请不要以这种方式使用getProperty 方法。请改为执行以下操作:fw.write(min + "," + max + System.getProperty("line.separator"));
  • 如何获取列标题名称“Min”、“Max”、“Average”,然后转移到新行进行输出?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2012-07-21
  • 2016-03-02
相关资源
最近更新 更多