我想知道为什么我会用新的日食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;
}
}
Run Code Online (Sandbox Code Playgroud)
Str*_*lok 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;
}
}
Run Code Online (Sandbox Code Playgroud)
您不需要显式关闭底层渠道.但是,如果你不使用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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
看看Java 7版本有多好:)
归档时间: |
|
查看次数: |
8728 次 |
最近记录: |