我今天遇到了一个我们实用工具类的问题。它是文件的帮助程序,包含一些静态文件复制例程。以下是相关方法和测试方法的提取。
问题在于有时setLastModified调用会失败,并返回false。
在我的PC上(Windows 7,最新的Java),我有时会收到“setLastModified失败”的消息(每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
。
transferTo
在 Windows 上不受支持,即它是模拟的,这就是为什么它总是传输整个文件,在 Linux 上可能不会传输所有内容,因此需要循环。我唯一看到setModified
失败的方式是文件被锁定。同时尝试使用唯一的文件名来排除任何并发代码。 - bestsss