简体   繁体   English

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

[英]“\n” not adding new line when saving the string to text using PrintWriter

I want to print a string to a text using out.print but the \\n in the string are not working. 我想使用out.print将字符串打印到文本,但字符串中的\\n不起作用。

Here is the code: 这是代码:

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();
    }
}

But in the saved file no new line is created, all the lines are after each other. 但是在保存的文件中没有创建新行,所有行都是相继的。 Any idea how to fix this? 知道如何解决这个问题吗? (beside adding out.println to all lines.) (旁边将out.println添加到所有行。)

Edit: I compile and run the code with windows command prompt and open the file with notepad. 编辑:我使用Windows命令提示符编译并运行代码并使用记事本打开文件。

Different platforms use different line separators. 不同的平台使用不同的行分隔符。

  • Windows use \\r\\n Windows使用\\r\\n
  • Unix-like platforms use \\n 类Unix的平台使用\\n
  • Mac now uses \\n too, but it used to use \\r . Mac现在也使用\\n ,但过去常常使用\\r

(You can see more information and variants here ) (您可以在此处查看更多信息和变体)

You can get your "local" line separator by using 您可以使用获取“本地”行分隔符

System.getProperty("line.separator")

eg 例如

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

However, it is easier to use %n in a string formatter: 但是,在字符串格式化程序中使用%n更容易:

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

If you are targeting a particular platform, you can just use the literal. 如果您要定位特定平台,则可以使用文字。

If you are using Java 7 then you can use System.lineSeparator()..see if this helps. 如果您使用的是Java 7,则可以使用System.lineSeparator()..看看这是否有帮助。 For older versions of Java you can use - System.getProperty("line.separator") 对于旧版本的Java,您可以使用 - System.getProperty(“line.separator”)

Example : System.out.println(System.lineSeparator()+"This is the second line"); 示例:System.out.println(System.lineSeparator()+“这是第二行”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM