How to write new line in Java FileOutputStream

北城以北 提交于 2019-12-17 16:56:27

问题


I want to write a new line using a FileOutputStream; I have tried the following approaches, but none of them are working:

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

回答1:


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?




回答2:


This should work. Probably you forgot to call 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 writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));

Alternatively you can use FileWriter instead of FileOutputStream from the beginning:

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.



来源:https://stackoverflow.com/questions/24243348/how-to-write-new-line-in-java-fileoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!