我从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
如您所见,标头缺少Run5
和Run6
。
我的问题是如何更新标题以包括新的列名?请注意,稍后可能会添加其他类,并且运行次数超过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();
}
答案 0 :(得分:0)
在进入写入步骤之前,您应该知道任何行的最大运行次数 您可以通过
int numRuns = 0
for (int i=0; i<classes.size(); i++) {
int rowSize = this.getRuns(classes.get(i));
if (rowSize > numRows) {
numRuns = rowSize;
}
}