我想知道为什么我会用新的日食Juno得到这个警告,尽管我认为我正确地关闭了所有东西。您能告诉我为什么我会在下面的代码中收到此警告吗?
public static boolean copyFile(String fileSource, String fileDestination)
{
try
{
// Create channel on the source (the line below generates a warning unassigned closeable value)
FileChannel srcChannel = new FileInputStream(fileSource).getChannel();
// Create channel on the destination (the line below generates a warning unassigned closeable value)
FileChannel dstChannel = new FileOutputStream(fileDestination).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
return true;
}
catch (IOException e)
{
return false;
}
}
答案 0 :(得分:16)
如果你在Java 7上运行,你可以使用像这样的新try-with-resources块,你的流将自动关闭:
public static boolean copyFile(String fileSource, String fileDestination)
{
try(
FileInputStream srcStream = new FileInputStream(fileSource);
FileOutputStream dstStream = new FileOutputStream(fileDestination) )
{
dstStream.getChannel().transferFrom(srcStream.getChannel(), 0, srcStream.getChannel().size());
return true;
}
catch (IOException e)
{
return false;
}
}
您无需显式关闭基础渠道。但是,如果您不使用Java 7,则应该以一种繁琐的旧方式编写代码,最后使用块:
public static boolean copyFile(String fileSource, String fileDestination)
{
FileInputStream srcStream=null;
FileOutputStream dstStream=null;
try {
srcStream = new FileInputStream(fileSource);
dstStream = new FileOutputStream(fileDestination)
dstStream.getChannel().transferFrom(srcStream.getChannel(), 0, srcStream.getChannel().size());
return true;
}
catch (IOException e)
{
return false;
} finally {
try { srcStream.close(); } catch (Exception e) {}
try { dstStream.close(); } catch (Exception e) {}
}
}
看看Java 7版本有多好:)
答案 1 :(得分:4)
您应始终在finally
关闭,因为如果异常增加,您将无法关闭资源。
FileChannel srcChannel = null
try {
srcChannel = xxx;
} finally {
if (srcChannel != null) {
srcChannel.close();
}
}
注意:即使您在catch
块中添加了回复,也会完成finally
块。
答案 2 :(得分:3)
eclipse警告你,你不能再引用FileInputStream
和FileOutputStream
。