gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:00:22 26 4
gpt4 key购买 nike

如何解决这个问题?

我收到以下错误:关闭此“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com