再次关闭此“FileOutputStream”声纳

时间:2017-05-26 12:26:04

标签: java sonarqube

我遇到了从声纳关闭“FileOutputStream”的麻烦。虽然我关闭了文件。从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();

            }

        }

如何解决?

1 个答案:

答案 0 :(得分:4)

使用try-with-resources语句。

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

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