2011-05-04 70 views
0

我正在網絡驅動器上創建一個文件,然後向其添加數據。時間寫入該文件失敗。在每次將數據保存到文件之前,是否有一種檢查文件是否可訪問的好方法,或者可以通過檢查其他方式來檢查數據是否已保存?Java,用什麼來代替PrintStream來獲取異常?

編輯: 現在我使用try-catch塊用的PrintStream在我的代碼:

 try 
     { 
      logfile = new File(new File(isic_log), "log_" + production); 
      //nasty workaround - we'll have a file the moment we assign an output stream to it 
      if (!logfile.exists()) 
      { 
        prodrow = production; 
      } 

      out = new FileOutputStream(logfile.getPath(), logfile.exists()); 
      p = new PrintStream(out); 
      if (prodrow != "") 
      { 
       p.println (prodrow); 
      } 
      p.println (chip_code + ":" + isic_number); 
      p.close(); 
     } 
     catch (Exception e) 
     { 
       logger.info("Got exception while writing to isic production log: " + e.getMessage()); 
     } 

所以可能是PrintStream的問題嗎? (PrintWriter and PrintStream never throw IOExceptions

+3

它不會在它失敗時拋出異常嗎?首先進行檢查並不會有太大的幫助,因爲在寫入過程中的任何時候它都可能無法使用。 – 2011-05-04 08:47:21

+1

打開文件之前檢查文件是否可訪問導致競爭條件,在網絡文件系統的情況下。 – 2011-05-04 08:48:19

回答

2

我會使用普通的BufferedWriter,並根據需要自行添加換行符。


正常F​​ileOutputStream操作應該在出現錯誤時拋出IOException。

AFAIK,唯一的例外是PrintWriter不拋出異常。相反,您需要調用checkError(),但它不會告訴您錯誤是什麼或發生了什麼。

我建議你在這種情況下不要使用PrintWriter。

+0

供參考:我現在在那裏使用PrintStream。發現這個線程:http://stackoverflow.com/questions/297303/printwriter-and-printstream-never-throw-ioexceptions – hs2d 2011-05-04 08:59:02

1

解決此問題的唯一合理方法是將嘗試寫入文件,並以適當的方式處理任何生成的異常。由於網絡的不可靠性,預先知道I/O操作是否會成功幾乎是不可能的。