如何解决这个问题关闭这个“FileOutputStream”

时间:2017-11-15 08:08:16

标签: java sonarqube

如何解决这个问题?

我收到以下错误:关闭此“FileOutputStream”。但我已经在finally块中关闭了它

public void initHistoryForOldFile(File oldFile, String filePath) throws PIDException {

        InputStream inStream = null;
        OutputStream outStream = null;

        try {

            File historyFile = new File(StringUtil.append(filePath, File.separator, "history"));
            FileUtils.ensureDirectory(historyFile);

            File oldHistoryFile = new File(StringUtil.append(filePath, File.separator, "history", File.separator, oldFile.getName()));
            oldHistoryFile.createNewFile();

            if (oldFile.exists()) {
                inStream = new FileInputStream(oldFile);
                outStream = new FileOutputStream(oldHistoryFile);

                byte[] buffer = new byte[PIDConstants.IMAGE_FILE_SIZE_LIMIT];

                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {

                    outStream.write(buffer, 0, length);

                }

                // delete the original file
                oldFile.delete();
            }

        } catch (IOException e) {
            LOGGER.error("Exception occured in historyUpdateForOldFIle", e);
        } finally {
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing inStream", e);
                }
            }
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    LOGGER.error("Exception occured whole closing outStream", e);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果使用java 7

您可以使用Try with resources

try(InputStream inStream = new FileInputStream(oldFile)){}
  

try-with-resources语句是一个声明一个或多个资源的try语句。资源是在程序完成后必须关闭的对象。 try-with-resources语句确保在语句结束时关闭每个资源。