由于某种原因,我的String部分由PrintWriter编写。因此,我在文件中获得部分文本。方法如下:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
} catch (IOException e) {
e.printStackTrace();
}
}
字符串
在我将文本打印到控制台的地方,我可以看到数据都在那里,没有丢失任何东西,但显然当PrintWriter完成其工作时,部分文本丢失了。
5条答案
按热度按时间lstz6jyr1#
在丢弃已打开的流之前,您应该始终使用
Writer#close
。这将释放JVM在文件系统上打开文件时必须占用的一些相当昂贵的系统资源。如果您不想关闭流,可以使用Writer#flush
。这将使您的更改在文件系统上可见,而无需关闭流。关闭流时,所有数据都会隐式刷新。流总是缓冲数据,以便只有在有足够的数据要写入时才写入文件系统。当流以某种方式认为数据 * 值得写入 * 时,它会不时地自动刷新其数据。写入文件系统是一项昂贵的操作(这会花费时间和系统资源),因此只有在确实有必要的情况下才应该这样做。因此,您需要手动刷新流的缓存,如果你想立即写。
一般来说,确保你总是关闭流,因为它们会占用相当多的系统资源。Java有一些机制可以在垃圾收集时关闭流,但这些机制只应该被视为最后的手段,因为流在实际被垃圾收集之前可以存活相当长的一段时间。因此,总是使用
try {} finally {}
来确保流被关闭,即使在打开流后出现异常。如果你不注意这一点,你最终会得到一个IOException
信号,表明你打开了太多的文件。你想这样修改你的代码:
字符串
tktrz96b2#
尝试在
out.print(text);
行之后使用out.flush();
下面是一个正确的方式来写一个文件:
字符串
unguejic3#
我测试了你的代码。你忘了关闭PrintWriter对象,即out.close
字符串
jmp7cifd4#
您必须始终在finally块中或使用Java 7 try-with-resources工具关闭流(这也将刷新它们):
字符串
或
型
如果不关闭流,不仅不会将所有内容都刷新到文件中,而且在某些时候,操作系统将没有可用的文件描述符。
kqlmhetl5#
你应该关闭你的文件:
字符串