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(),但都给出了相同的结果。为什么会留下两条线,如何避免?

最佳答案

刚刚试过你的代码,它按预期工作。
代码

try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.csv", true))) {

    bw.append("Text after writing");
    bw.append(System.lineSeparator());

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

测试.csv之前:
1. Text already in file before writing

测试.csv之后:
1. Text already in file before writing
2. Text after writing

可能您正在编辑的文件已经以新行结束。你可以考虑在附加之前检查一下。
注意:使用try-with-resource来简化代码。
注:测试时间:jre1.8.0_77,Win7(x64)

关于java - BufferedWriter行分隔符变为双行分隔符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40787795/

10-10 16:50