如何为fileinputstream和fileoutstream释放资源?



在我的veracode扫描中,我有非常低的漏洞:不适当的资源关闭或释放CWE ID 404

下面是我的代码:

public static boolean nioCopy(File source, File destination) {
boolean retval = false;

FileChannel inChannel = null, outChannel = null;

try {
inChannel = (new FileInputStream(source)).getChannel();
outChannel = (new FileOutputStream(destination)).getChannel();

long size = inChannel.size();
long position = 0;
while ( position < size )
{
position += inChannel.transferTo( position, WINDOWS_MAGIC_BUFFER_SIZE, outChannel );
}
retval = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
retval = false;
} catch (IOException e) {
e.printStackTrace();
retval = false;
} finally {
try {
if (inChannel != null) {
inChannel.close();
}

if (outChannel != null) {
outChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

return retval;
}

Veracode特别指向这一行:

outChannel = (new FileOutputStream(destination)).getChannel();

然而,我相信我在finally块中释放了资源。我指的是这个链接:http://javaelegance.blogspot.com/2015/10/improper-resource-shutdown-or-release.html

我在这里做错了什么?

假设Java 8或更高版本,对资源语句使用try。见https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。它基本上会自动为你关闭可关闭对象。

try (inChannel = (new FileInputStream(source)).getChannel()) {
//Use inChannel
}
catch(IOException ex) {
//Handle exception
}