写入后的空白文件?

所以我一直在尝试为我的一个朋友写一个Bukkit插件,由于某种原因,配置生成不起作用。 有问题的代码如下,我很乐意添加人们需要的任何代码来帮助我解决这个问题。 当我运行该程序时,创建的配置文件最终为空白。 测试文件很好(我通过简单地注释删除文件的行来测试)但是一旦我尝试获得多行就失败了。 有人可以帮忙吗?

PrintWriter out = new PrintWriter(new FileWriter(config)); out.println("########################################"); out.println("# hPlugin is written by newbiedoodle #"); out.println("########################################"); out.println("# ----- Plugin config file ----- #"); out.println("########################################"); out.println("NOTE: Do not edit the config file besides changing the values - it may result in errors."); out.println("--------------"); out.println("Strikes before being banned?"); out.println("3"); out.println("Godmode?"); out.println("true"); out.println("First time running the plugin?"); out.println("true"); out.println("Curse protection?"); out.println("true"); out.println("Emergency shelter?"); out.println("true"); out.println("Path building?"); out.println("true"); out.println("Blocked words/phrases (Separate with comma)"); out.println("[censored]"); out.close(); System.out.println("Successfully wrote defaults to config"); 

整个事情都包含在try / catch循环中,以捕获可能弹出的任何错误。 我觉得我错过了一些非常明显的东西,但我找不到它是什么。

  • config是一个File对象,它包含了它需要的路径,所以我不认为就是这样

  • 我让程序几乎单独执行所有操作,以便我可以准确地告诉用户错误发生的位置,因此文件就在try / catch之外创建。

你需要打电话……

 out.flush(); 

……在你打电话之前……

 out.close(); 

PrintWriter使用内存中的缓冲区来更有效地使用磁盘。 您需要调用flush()来告诉PrintWriter写入您的数据。

很可能你已经多次运行这个并且你正在写一个文件并检查另一个文件。 我怀疑文件名是相同的,但目录,可能基于工作目录不是你认为的。

在这种情况下关闭调用flush,因为PrintWriter使用BufferedWriter而另一个Writer类没有缓冲。

  251 public void flush() throws IOException { 252 synchronized (lock) { 253 flushBuffer(); 254 out.flush(); 255 } 256 } 257 258 public void close() throws IOException { 259 synchronized (lock) { 260 if (out == null) { 261 return; 262 } 263 try { 264 flushBuffer(); 265 } finally { 266 out.close(); 267 out = null; 268 cb = null; 269 } 270 } 271 } 

完成后,您需要刷新或关闭流。 在退出之前,两者都非常重要。 关闭将自动调用flush()。