FileWriter 输出到 csv 文件是空白的
FileWriter output to csv file is blank
FileWriter outfile = new FileWriter("ouput.csv", true); //true = append
for(int len = 0; len < tempList.size(); len++) {
LineItem tempItem = tempList.get(len);
if ( len == 0 ) {
lastTime = tempItem.getTimeEnd();
tempItem.setStatus("OK");
//out
output( tempItem.toCSV(), outfile);
} else {
if ( tempItem.getTimeStart().compareTo(lastTime) <= 0 ) {
//WARN
if (!tempItem.getStatus().equals("OVERLAP")) {
tempItem.setStatus("WARN");
}
} else {
//OK
//System.out.println( "OK ;" + tempItem.toCSV());
if (!tempItem.getStatus().equals("OVERLAP")) {
tempItem.setStatus("OK");
}
}
// file out write
output( tempItem.toCSV(), outfile);
lastTime = tempItem.getTimeEnd();
}
}
}
private static void output(String line, FileWriter outfile) throws IOException {
System.out.println(line);
// Write each line to a new csv file
outfile.write(line + "\n");
}
为什么我的 output.csv 文件是 0 kb 并且是空的?但是当我打印到行时,我在控制台中看到了每个字符串...
在output( tempItem.toCSV(), outfile);
之后请添加以下语句。你忘了flush
。 Close
自动为你flush
。
outfile.close();
您没有关闭 FileWriter
。
NB 冲洗和关闭的建议是多余的。
当你flush(outfile)
它会被写入文件。
当您 close(outfile)
时,它也会自动刷新。有时你想在其他时候 flush()
,但通常没有必要。您应该总是在完成文件后关闭文件。
从 Java 7 开始,使用 try-with-resources 通常是个好主意:
try(FileWriter outfile = new FileWriter("output.csv", true)) {
// code that writes to outfile
}
因为FileWriter
实现了Closeable
,当执行离开这个块时它会自动调用outfile.close()
。
FileWriter outfile = new FileWriter("ouput.csv", true); //true = append
for(int len = 0; len < tempList.size(); len++) {
LineItem tempItem = tempList.get(len);
if ( len == 0 ) {
lastTime = tempItem.getTimeEnd();
tempItem.setStatus("OK");
//out
output( tempItem.toCSV(), outfile);
} else {
if ( tempItem.getTimeStart().compareTo(lastTime) <= 0 ) {
//WARN
if (!tempItem.getStatus().equals("OVERLAP")) {
tempItem.setStatus("WARN");
}
} else {
//OK
//System.out.println( "OK ;" + tempItem.toCSV());
if (!tempItem.getStatus().equals("OVERLAP")) {
tempItem.setStatus("OK");
}
}
// file out write
output( tempItem.toCSV(), outfile);
lastTime = tempItem.getTimeEnd();
}
}
}
private static void output(String line, FileWriter outfile) throws IOException {
System.out.println(line);
// Write each line to a new csv file
outfile.write(line + "\n");
}
为什么我的 output.csv 文件是 0 kb 并且是空的?但是当我打印到行时,我在控制台中看到了每个字符串...
在output( tempItem.toCSV(), outfile);
之后请添加以下语句。你忘了flush
。 Close
自动为你flush
。
outfile.close();
您没有关闭 FileWriter
。
NB 冲洗和关闭的建议是多余的。
当你flush(outfile)
它会被写入文件。
当您 close(outfile)
时,它也会自动刷新。有时你想在其他时候 flush()
,但通常没有必要。您应该总是在完成文件后关闭文件。
从 Java 7 开始,使用 try-with-resources 通常是个好主意:
try(FileWriter outfile = new FileWriter("output.csv", true)) {
// code that writes to outfile
}
因为FileWriter
实现了Closeable
,当执行离开这个块时它会自动调用outfile.close()
。