PrintWriter仅写入部分文本

由于某种原因,我的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完成其工作时,显然文本的一部分会丢失……我很无能为力……

在丢弃已打开的流之前,您应始终使用Writer#close您的流。 这将释放JVM在文件系统上打开文件时必须要求的一些相当昂贵的系统资源。 如果您不想关闭流,可以使用Writer#flush 。 这将使您的更改在文件系统上可见,而不关闭流。 关闭流时,将隐式刷新所有数据。

Streams总是缓冲数据,以便在有足够的数据写入时只写入文件系统。 当流以某种方式认为数据值得写时,流会不时地自动刷新其数据。 写入文件系统是一项昂贵的操作(它需要时间和系统资源),因此只有在确实需要时才应该这样做。 因此,如果您希望立即写入,则需要手动刷新流的缓存。

通常,请确保始终关闭流,因为它们使用了相当多的系统资源。 Java有一些关闭垃圾收集流的机制,但这些机制应该只被视为最后的手段,因为流可以在实际垃圾收集之前存活很长时间。 因此,始终使用try {} finally {}来确保流关闭,即使在打开流之后的exception也是如此。 如果你不注意这一点,你将得到一个IOException信号,表明你打开了太多文件。

您想要像这样更改代码:

 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"); try { out.print(text); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } 

尝试使用out.flush(); 在行out.print(text);

这是在文件中写入的正确方法:

 public void new_file_with_text(String text, String fname) { try (FileWriter f = new FileWriter(fname)) { f.write(text); f.flush(); } catch (IOException e) { e.printStackTrace(); } } 

我测试了你的代码。 您忘记关闭PrintWriter对象,即out.close

 try { f = new File(fname); f.createNewFile(); System.out.println(text); PrintWriter out = new PrintWriter(f, "UTF-8"); out.print(text); out.close(); // <-------------- } catch (IOException e) { System.out.println(e); } 

您必须始终关闭您的流(也将刷新它们),在finally块中,或使用Java 7 try-with-resources工具:

 PrintWriter out = null; try { ... } finally { if (out != null) { out.close(); } } 

要么

 try (PrintWriter out = new PrintWriter(...)) { ... } 

如果不关闭流,不仅不会将所有内容刷新到文件中,而且在某个时候,您的操作系统将缺少可用的文件描述符。

你应该关闭你的文件:

 PrintWriter out = new PrintWriter(f, "UTF-8"); try { out.print(text); } finally { try { out.close(); } catch(Throwable t) { t.printStackTrace(); } }