【问题标题】:Close this "FileOutputStream" sonar again [duplicate]再次关闭此“FileOutputStream”声纳[重复]
【发布时间】:2017-05-26 12:26:03
【问题描述】:

我遇到了 close the "FileOutputStream" from sonar 的麻烦。尽管我关闭了文件。从声纳的文件中,我不明白这个错误。 我看了帖子 SONAR issue - Close this FileInputStream。 这也不能解决我的问题。

 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();

            }

        }

如何解决?

【问题讨论】:

  • 将 declalation 放入 try 中,因为在 try FileOutputStream ms = new FileOutputStream(model_path); 之前不使用对象 ms // 这个正在产生错误。

标签: java sonarqube


【解决方案1】:

使用 try-with-resources 语句。

如果在 try 块之前的任何代码行引发异常,则 FileOutputStream 永远不会关闭。因此声纳警告。

另外,缩进你的代码,不要捕捉异常(你应该有另一个警告),不要像你正在做的那样忽略异常。

【讨论】:

  • try-with-resources 声明。请举个例子
  • 认真的吗?使用谷歌。天哪。对于软件开发人员来说,在地址栏中输入“try-with-resources”,按回车键,然后点击第一个链接,真的那么复杂吗?
  • 不适合我。这是给其他人的。 try(ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(model_path))){ }
  • 阅读此答案的其他人也应该能够做到这一点。
  • 应该禁止无法谷歌“try-with-resources”的人编写软件。
猜你喜欢
  • 2016-06-21
  • 2017-05-06
  • 2016-08-24
  • 2017-11-16
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多