java 文本文件换行

java text file new line

我正在尝试捕获信息,然后将其解析为 txt 文件。

我曾尝试使用 \n 来创建一个新行,但程序似乎将字符串追加到同一行。

try {

    FileWriter mother = new FileWriter(file, true);
    mother.write(newsHeadline.attr("title") + '\n');
    mother.close();
} catch(IOException e) {    
}       

有什么建议吗?

使用 System.lineSeparator() 可能对您有所帮助

mother.write(newsHeadline.attr("title") + System.lineSeparator());

如果您正在使用 Java 7/8:

try (PrintWriter out = new PrintWriter(new FileWriter(file, true), true)) {
    out.println(newsHeadline.attr("title"));
}

获取行分隔符的official方法如下:

String newline = System.getProperty("line.separator");

所以我会使用:

myPrintWriter.print("Something." + newline);

使用系统 属性 的优势在于,无论 运行 在哪个平台上,它都会发声,因为 属性 会根据平台而变化。 (Windows / Unix)