繁体   English   中英

如何附加到 CSV 文件中的特定行

[英]How to append to a specific row in CSV file

我有从 CSV 文件中读取的以下数据:

Class    Total     Step     Run1    Run2   Run3    Run4
Timer    15        2        10.5    3.6    5.5     8

稍后,将添加具有可变运行大小的其他类。 例如,将添加具有 6 次运行的类Optimiser ,CSV 将类似于:

Class     Total     Step     Run1    Run2   Run3    Run4
Timer     15        2        10.5    3.6    5.5     8
Optimiser 26        6        6       10     5       1.5    16    9

如您所见,标头缺少Run5Run6

我的问题是如何更新标题以包含新的列名? 请注意,其他类可能会在稍后添加,运行次数超过 6 次。

我编写的用于写入 CSV 的代码是:

  try {
      BufferedWriter out = new BufferedWriter(new FileWriter(f, true));
      if (f.length() == 0L) {
          out.write("Class");
          out.write(",");
          out.write("Total");
          out.write(",");
          out.write("Step");
          out.write(",");
          for (int i = 1; i <= numRuns; i++) {
              out.write(String.valueOf(i));
              out.write(",");
          }
          out.write("\n");
      }

      for (int i = 0; i < classes.size(); i++) {
          out.write(classes.get(i));
          out.write(",");

          out.write(totals.get(i));
          out.write(",");

          out.write(steps.get(i));
          out.write(",");

          List<Double> runs = this.getRuns(classes.get(i));
          for (double x: runs) {
              out.write(String.valueOf(x));
              out.write(",");
          }
          out.write("\n");
      }
      out.close();

  } catch (IOException e) {
      e.printStackTrace();
  }

在进入写入步骤之前,您应该知道任何行中的最大运行次数,您可以通过

int numRuns = 0
for (int i=0; i<classes.size(); i++) {
    int rowSize = this.getRuns(classes.get(i));
    if (rowSize > numRows) {
        numRuns = rowSize;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM