如何在 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

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

How to write new line in Java FileOutputStream

javanewlinefileoutputstream

提问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 PrintWriterand enjoy its println()methods:

然而,这不是编写文本的首选方式。你应该用PrintWriterprintln()来包装你的输出流并享受它的方法:

PrintWriter writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));

Alternatively you can use FileWriterinstead of FileOutputStreamfrom 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()当你完成你的工作。