Java 如何解决这一问题;FileOutputStream“;
如何解决这个问题 我收到以下错误:关闭此“FileOutputStream”。但我已经把它关在最后一个街区了Java 如何解决这一问题;FileOutputStream“;,java,sonarqube,Java,Sonarqube,如何解决这个问题 我收到以下错误:关闭此“FileOutputStream”。但我已经把它关在最后一个街区了 public void initHistoryForOldFile(File oldFile, String filePath) throws PIDException { InputStream inStream = null; OutputStream outStream = null; try { Fil
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);
}
}
}
}
如果使用Java7
你可以用
try with resources语句是声明一个或多个资源的try语句。资源是一个必须在程序完成后关闭的对象。try with resources语句确保在语句末尾关闭每个资源
如果使用Java7
你可以用
try with resources语句是声明一个或多个资源的try语句。资源是一个必须在程序完成后关闭的对象。try with resources语句确保在语句末尾关闭每个资源
你到底得到了什么错误?编译时错误?运行时错误?而且。。。请添加完整且准确的错误消息。请显示完整的错误堆栈。为什么(a)使用
file.createNewFile()
创建一个新文件,然后(b)使用new FileOutputStream(…)
创建另一个新文件?不要这样浪费操作系统的时间。@Seelenvirtuose:这个错误来自sonarqube。这不是编译/运行时错误。我在声纳中得到了这个警告,警告线是outStream=newfileoutputstream(oldHistoryFile);带有消息“Close this”FileOutputStream。“SonarQube和SonarJava analyzer的版本是什么?”?尝试更新到最新版本,分析器中针对此类场景进行了一些修复。您到底得到了什么错误?编译时错误?运行时错误?而且。。。请添加完整且准确的错误消息。请显示完整的错误堆栈。为什么(a)使用file.createNewFile()
创建一个新文件,然后(b)使用new FileOutputStream(…)
创建另一个新文件?不要这样浪费操作系统的时间。@Seelenvirtuose:这个错误来自sonarqube。这不是编译/运行时错误。我在声纳中得到了这个警告,警告线是outStream=newfileoutputstream(oldHistoryFile);带有消息“Close this”FileOutputStream。“SonarQube和SonarJava analyzer的版本是什么?”?尝试更新到最新版本,analyzer中针对此类场景进行了一些修复
try(InputStream inStream = new FileInputStream(oldFile)){}