Java NewLine“\n”在保存到文本文件时不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25103655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:20:59  来源:igfitidea点击:

Java NewLine "\n" not working in save to text file

javafile-io

提问by GJ Shumel

Here is my code:

这是我的代码:

public String display() {
    return "\n......................\nFixed Employee:\n" + 
           "Name: " + super.fullName() + 
           "\nSalary: " + salary() + 
           " tk\n......................";
}

But when I'm invoking this method from main class, "\n" newLine not working. just showing one line output. Will you plz help to solve the problem?

但是当我从主类调用这个方法时,"\n" newLine 不起作用。只显示一行输出。你会帮助解决问题吗?

Thanks

谢谢

回答by Unihedron

For saving in files use \r\n. \nas new lines is viable on printstreams but not writing to files.

要保存在文件中,请使用\r\n. \n因为新行在打印流上是可行的,但不能写入文件。

回答by tmarwen

You may need the system independent line separator as it might differ from one OS to another. Just replace the \nwith the value of line separator:

您可能需要独立于系统的行分隔符,因为它可能因操作系统而异。只需将\n替换为行分隔符的值:

  • I can be retrieve as you load any system property:
  • 当您加载任何系统属性时,我可以被检索:
    public String display() { 
      String separator = System.getProperty("line.separator"); // Load the system property using its key.
      return "\n......................\nFixed Employee:\n" 
        + "Name: " 
        + super.fullName() + 
        "\nSalary: " 
        + salary() 
        + " tk\n......................"
      .replace("\n", separator); // replace the \n before returning your String 
    }
  • Or simply use System#lineSeparatormethod as @Deepanshu Bedi suggested:
  • 或者简单地使用System#lineSeparator@Deepanshu Bedi 建议的方法:
    public String display() { 
      String separator = System.lineSeparator(); // Consider it as a shortcut.
      return "\n......................\nFixed Employee:\n" 
        + "Name: " 
        + super.fullName() + 
        "\nSalary: " 
        + salary() 
        + " tk\n......................"
      .replace("\n", separator); // replace the \n before returning your String 
}