我今天遇到了一个与我们的实用程序类有关的问题。它是文件的助手,包含一些静态文件复制例程。以下是提取的相关方法和测试方法。
问题是有时 setLastModified 调用会失败,返回 false。
在我的 PC(Windows 7,最新的 Java)上,我有时会收到“setLastModified failed”消息(1000 次中大约有 25 次)。
我现在已经通过删除 FileChannel.close 调用解决了这个问题,但我更愿意理解为什么会发生这种情况,即使这是正确的解决方案。
有没有人遇到同样的问题?
private void testCopy() throws FileNotFoundException, IOException {
File src = new File("C:\\Public\\Test-Src.txt");
File dst = new File("C:\\Public\\Test-Dst.txt");
for (int i = 0; i < 1000; i++) {
copyFile(src, dst);
}
}
public static void copyFile(final File from, final File to) throws FileNotFoundException, IOException {
final String tmpName = to.getAbsolutePath() + ".tmp";
// Copy to a .tmp file.
final File tmp = new File(tmpName);
// Do the transfer.
transfer(from, tmp);
// Preserve time.
if (!tmp.setLastModified(from.lastModified())) {
System.err.println("setLastModified failed!");
}
// In case there's one there already.
to.delete();
// Rename it in.
tmp.renameTo(to);
}
public static void transfer(final File from, final File to) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
transfer(in, out);
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
}
public static void transfer(final FileInputStream from, final FileOutputStream to) throws IOException {
FileChannel srcChannel = null;
FileChannel dstChannel = null;
//try {
srcChannel = from.getChannel();
dstChannel = to.getChannel();
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
//} finally {
// if (null != dstChannel) {
// dstChannel.close();
// }
// if (null != srcChannel) {
// srcChannel.close();
// }
}
}
编辑:我更改了代码以仅关闭 Streams
而不是 FileChannel
因为研究建议关闭 FileChannel
也会关闭 Stream
。
最佳答案
在对拥有 Java 库源的各种站点进行一些研究之后,它看起来非常像 FileChannel.close
最终调用 FileInputStream.close
或 FileOutputStream.close
其父对象。
这向我建议您应该关闭 FileChannel 或 Stream,但不能同时关闭这两者。
鉴于此,我正在更改我的原始帖子以反射(reflect)一种正确的方法,即关闭 Stream
而不是 Channel
。
关于java - 我应该关闭 FileChannel 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8066130/