如何在 Java FileOutputStream 中编写新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24243348/
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
How to write new line in Java FileOutputStream
提问by Pavan Patidar
I want to write a new line using a FileOutputStream
; I have tried the following approaches, but none of them are working:
我想用FileOutputStream
;写一个新行 我尝试了以下方法,但都没有奏效:
encfileout.write('\n');
encfileout.write("\n".getbytes());
encfileout.write(System.getProperty("line.separator").getBytes());
采纳答案by Teddy
It could be a viewer problem... Try opening the file in EditPlus or Notepad++. Windows Notepad may not recognise line feed of another operating system. In which program are you viewing the file now?
这可能是查看器问题...尝试在 EditPlus 或 Notepad++ 中打开文件。Windows 记事本可能无法识别其他操作系统的换行符。您现在正在哪个程序中查看文件?
回答by AlexR
This should work. Probably you forgot to call encfileout.flush()
.
这应该有效。可能你忘记打电话了encfileout.flush()
。
However this is not the preferred way to write texts. You should wrap your output stream with PrintWriter
and enjoy its println()
methods:
然而,这不是编写文本的首选方式。你应该用PrintWriter
它println()
来包装你的输出流并享受它的方法:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));
Alternatively you can use FileWriter
instead of FileOutputStream
from the beginning:
或者,您可以使用FileWriter
而不是FileOutputStream
从一开始:
FileWriter fw = new FileWriter("myfile");
PrintWriter writer = new PrintWriter(fw);
Now just call
现在只需打电话
writer.println();
And do not forget to call flush()
and close()
when you finish your job.
不要忘记打电话flush()
,close()
当你完成你的工作。