PrintWriter not printing out complete string

蓝咒 提交于 2019-12-11 03:08:27

问题


I have the following code

FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
H.print(split[split.length - 2]);
H.print("END");

When I examine the txt however, the last text is NOT 'END', but part of a word in the string. It is "repa"

When I do this

FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
System.out.print(split[split.length - 2]);

The last bit of text I get is the number '49' - this is correct.

It appears that the PrintWriter is not fully writing out the string. However, when I do this

FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
H.print(split[split.length - 2]);
H.println(pdfInText)://Another string
H.print("END");

The 'original' text now actually finishes - what is this?


回答1:


Do you close the PrintWriter? From its javadoc

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println() methods is invoked, rather than whenever a newline character happens to be output. The println() methods use the platform's own notion of line separator rather than the newline character.

If you do close the PrintWriter (and not the FileWriter!) try a flush() after printing, to force that.



来源:https://stackoverflow.com/questions/13806733/printwriter-not-printing-out-complete-string

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