2014-08-30 93 views
0

我無法弄清楚爲什麼我的代碼出現上述錯誤。每次調用方法時,我都會創建一個FileWriter和BufferedWriter的新實例,但顯然該流已經關閉。寫入文件:IOException:流關閉

public static void addSpawn(Location spawn) 
{ 
    File spawns = new File("spawns.dat"); 

    FileWriter write = null; 
    BufferedWriter out = null; 

    try 
    { 
     write = new FileWriter(spawns, true); 
     out = new BufferedWriter(write); 

     out.write(locToStr(spawn)); 
     out.newLine(); 
    } 
    catch(Exception e) 
    { 
     System.out.println("Error writing spawn file: " + e.getMessage()); 
    } 
    finally 
    { 
     if(write != null) 
     { 
      try 
      { 
       write.close(); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 
     } 

     if(out != null) 
     { 
      try 
      { 
       out.close(); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

任何幫助將不勝感激。

+0

請顯示完整的堆棧跟蹤,包括指示您已發佈代碼中的哪一行引發異常。 – 2014-08-30 20:09:23

回答

2

BufferedWriter包裝目標Writer。當你close()它,它在關閉它之前試圖flush底層目標Writer

在你的代碼中,你調用close()對目標FileWriter調用closeBufferedWriter。當BufferedWriter#close()試圖調用FileWriter上的flush時,該FileWriter已關閉,從而引發異常。

您需要先關閉BufferedWriter。更好的是,使用try-with-resources

try (FileWriter write = new FileWriter(spawns, true); BufferedWriter out = new BufferedWriter(write);) { 
+0

感謝您的理解!我完全忘記了他們在關門時沖水,並且心不在焉地以錯誤的順序關閉他們。再次感謝! – 2014-08-30 20:21:39

相關問題