java - 如何解决这个问题关闭这个 "FileOutputStream"

标签 java sonarqube

如何解决这个问题?

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

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

最佳答案

如果使用 java 7

您可以使用Try with resources

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

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

关于java - 如何解决这个问题关闭这个 "FileOutputStream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47302271/

相关文章:

java.lang.NoClassDefFoundError : com/fasterxml/jackson/core/JsonFactory

javascript - 使用lcov和istanbul时如何忽略Javascript代码覆盖率中的某些语句?

java - Log4j 不将日志写入数据库

java - 当 tomcat 服务器运行时,然后我的 java 类运行

Java Riak 连接问题

java - 尝试使用多个资源会导致 Sonar qube 问题

node.js - 运行 npm run test 时无法从 'sonar-request' 找到模块 'api.js'

java - Sonar 死存储到局部变量

sonarqube - Sonarqube 6.X 中的仪表板已被删除?

java - 在 Java 中,如何用一个对象填充 arrayList 的一半,用另一个对象填充一半?