2017-05-26 91 views
-1

我遇到了問題關閉了聲納的「FileOutputStream」。儘管我關閉了文件。從Sonar的文件中,我不明白這個錯誤。我看了帖子 SONAR issue - Close this FileInputStream。 這也不能解決我的問題。再次關閉「FileOutputStream」聲納

public void trainL2lSupport(String training_path, String model_path) throws Exception { 
      BasicConfigurator.configure(); 

      String[] options = { "-s 1" }; 
      FileOutputStream ms = new FileOutputStream(model_path); // This one is producing the error. 

      classifier.setOptions(options); 
      logger.info(msg + classifier.globalInfo()); 
      loader.setFile(new File(training_path)); 
      Instances data_set = loader.getDataSet(); 
      data_set.setClassIndex(data_set.numAttributes() - 1); 
      classifier.buildClassifier(data_set); 
      Evaluation evaluation = new Evaluation(data_set); 
      evaluation.crossValidateModel(classifier, data_set, 40, new Random(1)); 
      logger.info(evaluation.toSummaryString()); 
      logger.info(msg1 + timer.stop()); 

      // oos = new ObjectOutputStream(ms); 
      try { 


      ObjectOutputStream oos = new ObjectOutputStream(ms); 
      oos.writeObject(classifier); 
      oos.flush(); 

      oos.close(); 


      logger.info(msg3+ evaluation.toSummaryString()); 
      logger.info(msg1 + timer.stop()); 

      logger.info("File closed safetly"); 
      } catch(Exception e) { 

      } 

      finally { 
       ms.close(); 

      } 

     } 

如何解決?

+0

將try聲明放入try中,因爲ms之前沒有使用過FileOutputStream ms = new FileOutputStream(model_path); //這是產生錯誤。 –

回答

4

使用try-with-resources語句。

如果在try塊之前的任何代碼行引發異常,FileOutputStream從不關閉。因此聲納警告。另外,縮進你的代碼,不要捕獲異常(你應該有另一個警告),並且不要忽略像你這樣的異常。

+0

試用資源聲明。請舉例 – Kumaresp

+2

認真?使用谷歌。天啊。對於軟件開發人員來說,在地址欄中輸入「試用資源」,點擊回車並點擊第一個鏈接,這真的很複雜嗎? –

+0

這不適合我。這是爲了其他人。嘗試(OOS的ObjectOutputStream =新的ObjectOutputStream(新FileOutputStream中(model_path))){ \t \t \t \t} – Kumaresp