如何在Java FileOutputStream中写入新行

20

我想使用 FileOutputStream 写入新行,但我尝试了以下方法,但都没有成功:

encfileout.write('\n');
encfileout.write("\n".getbytes());
encfileout.write(System.getProperty("line.separator").getBytes());

定义“不工作”。 - Christoffer Hammarström
它不会换行。 - Pavan Patidar
@PavanPatidar:它正在写入一个新行。肯定的。 - Martijn Courteaux
2
尝试执行encfileout.write("Fant".getbytes()); encfileout.write("\n".getbytes()); encfileout.write("astic".getbytes()); 如果您在单行上看到整个单词,则确认了您的问题。特别是,encfileout.write(System.getProperty("line.separator").getbytes()); 应该可以工作。 - Teddy
@Teddy:谢谢,你说得对,这只是一个显示问题,notepad++ 正确地显示了我的数据。再次感谢你的关注。 - Pavan Patidar
显示剩余3条评论
5个回答

20

这应该可以工作。可能是您忘记调用encfileout.flush()

但是这不是编写文本的首选方式。您应该使用PrintWriter包装您的输出流,并享受它的println()方法:

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

或者你可以一开始就使用FileWriter而不是FileOutputStream

FileWriter fw = new FileWriter("myfile");
PrintWriter writer = new PrintWriter(fw);

现在只需调用

writer.println();

不要忘记在完成工作时调用 flush()close()


希望你不介意我添加了缺失的字符集参数。 - Christoffer Hammarström
@Pavan,您能解释一下为什么这不是您要找的答案,以便可以修改答案或提供另一个答案吗? - Edd
FileWriter和PrintWriter都是功能丰富的。PrintWriter的println()非常好用!!! - Amol Dixit

10

可能是查看器出了问题...尝试在EditPlus或Notepad++中打开文件。 Windows记事本可能无法识别其他操作系统的换行符。您现在在哪个程序中查看该文件?


4

要添加换行,请使用

fileOutputStream.write(10);

这里的十进制值 10 表示 ASCII 编码中的换行符。


4
String lineSeparator = System.getProperty("line.separator");
<br>
fos.write(lineSeparator.getBytes());

请考虑在您的答案中添加某种形式的解释。仅提供代码的答案通常是不鼓励的。 - Axe319

0
您可以使用 Fos.write(System.lineSeparator().getBytes())。 这对我有效。

1
你的回答可以通过添加更多的支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便其他人可以确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接