I came across an issue with one of our utility classes today. It is a helper for files and contains some static file copy routines. Below are the relevant methods extracted along with a test method.
The problem is that sometimes the setLastModified call fails, returning false.
On my PC (Windows 7, latest Java) I sometimes get the "setLastModified failed" message (About 25 times out of 1000).
I have worked around the problem right now by removing the FileChannel.close calls but I would much prefer to understand why this is happening, even if that is the correct solution.
Does anyone else get the same problem?
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();
// }
}
}
Edit: I have changed the code to only close the Streams
s and not the FileChannel
s because research suggests closing the FileChannel
also closes the Stream
.