BufferedWriter bw = new BufferedWriter(new FileWriter("test.csv", true));
bw.append(System.lineSeparator());
bw.append("Text after writing"));
以上代码将导致以下内容:
Text already in file before writing
Text after writing
如果没有System.lineSeparator(),它将变为:
Text already in file before writingText after writing
我想要的是:
Text already in file before writing
Text after writing
我也试过了\ n和bw.newLine(),但都给出了相同的结果。为什么要留下2行,以及如何避免它?
答案 0 :(得分:0)
刚试过你的代码,它按预期工作。
<强>代码强>:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.csv", true))) {
bw.append("Text after writing");
bw.append(System.lineSeparator());
} catch (IOException e) {
e.printStackTrace();
}
之前test.csv :
1. Text already in file before writing
test.csv 之后:
1. Text already in file before writing
2. Text after writing
您正在编辑的文件可能已经以新行结束。你可以考虑在追加之前检查一下。
注意:使用try-with-resource代码简化。
注意:测试时间:jre1.8.0_77,Win7(x64)