java FileOutputStream 中的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11063805/
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-10-31 03:38:44  来源:igfitidea点击:

New line in FileOutputStream

javaoutputstreamfileoutputstream

提问by nr5

Ascii value of next line is 10. so i tried this...

下一行的 Ascii 值为 10。所以我尝试了这个...

 FileOutputStream os = new  FileOutputStream(f, true);
    os.write(10);  // this should get me to next line ?
    os.write(b);   // b is a byte array...

回答by Hyman

You should take care of managing crossplatform line separator, this can be retrieved in many ways:

您应该注意管理跨平台行分隔符,这可以通过多种方式检索:

  • System.getProperty("line.separator")
  • System.lineSeparator()(only Java7)
  • String.format("%n")
  • System.getProperty("line.separator")
  • System.lineSeparator()(仅 Java7)
  • String.format("%n")

Then you should take care of using a DataOutputStreamwrapped around your FileOutputStream, this because you will be allowed to choose many better methods like

然后你应该注意使用DataOutputStream环绕你的FileOutputStream,这是因为你将被允许选择许多更好的方法,比如

  • writeChars(String str)
  • writeBytes(String str)
  • writeUTF(String str)
  • writeChars(String str)
  • writeBytes(String str)
  • writeUTF(String str)

so that you will use the most suitable for your situation.

以便您使用最适合您的情况。

Mind also that writing a byte array directly on the stream creates binary data, which is somewhat opposite to using newlines (which are text instead).

还要注意,直接在流上写入字节数组会创建二进制数据,这与使用换行符(而是文本)有些相反。

回答by Martin Matula

On windows you need to use 13 and 10 as line separator (CR, LF) - i.e.:

在 Windows 上,您需要使用 13 和 10 作为行分隔符(CR、LF) - 即:

os.write(13);
os.write(10);

Hence, if you want your app to be platform independent, you should use whatever is in the line.separator system property as Hyman suggests.

因此,如果您希望您的应用程序独立于平台,您应该按照 Hyman 的建议使用 line.separator 系统属性中的任何内容。