简体   繁体   中英

How to solve this Close this "FileOutputStream"

How to solve this?

I am getting the below error : Close this "FileOutputStream". but i have closes it already in 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);
                }
            }
        }
    }

If using java 7

You can use 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.

try(InputStream instream = new fileinputstream(oldFile)){};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM