使用 PrintWriter 将字符串保存为文本时,“\n”不添加新行

"\n" not adding new line when saving the string to text using PrintWriter

我想使用 out.print 将字符串打印到文本,但字符串中的 \n 不起作用。

代码如下:

import java.io.PrintWriter;

public class LetterRevisited{
    public static void main(String[] args)throws Exception
    {
        PrintWriter out = new PrintWriter("Test.txt");
        out.println("This is the first line\n" +
        "This is the second line" );
    out.close();
    }
}

但是在保存的文件中没有创建新行,所有行都是一个接一个。 知道如何解决这个问题吗? (除了向所有行添加 out.println 之外。)

编辑:我使用 windows 命令提示符编译和 运行 代码,并使用记事本打开文件。

不同的平台使用不同的行分隔符。

  • Windows 使用 \r\n
  • 类 Unix 平台使用 \n
  • Mac 现在也使用 \n,但它以前使用 \r

(您可以看到更多信息和变体here

您可以使用

获取 "local" 行分隔符
System.getProperty("line.separator")

例如

out.println("Hello" + System.getProperty("line.separator") + "World");

但是,在字符串格式化程序中使用 %n 更容易:

out.printf("Hello%nWorld%n");

如果您的目标是特定平台,您可以只使用文字。

如果您使用的是 Java 7,那么您可以使用 System.lineSeparator()..看看这是否有帮助。对于旧版本的 Java,您可以使用 - System.getProperty("line.separator")

示例: System.out.println(System.lineSeparator()+"This is the second line");