Friday, May 4, 2012

Find the bug - part 3 (Windows edition)

I have come across a strangeness with Java on Windows with regards to file handling, i.e. the following code:

Logger logger = LoggerFactory.getLogger();
FTPClient ftpClient = new FTPClient(); // from commons-net
public void upload(File file) {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
this.logger.debug("Uploading file");
if (this.ftpClient.storeFile(file.getName(), is)) {
this.moveToSentDirectory(file);
}
else {
this.logger.error("Failure uploading file");
}
}
catch (Exception e) {
this.logger.error("Failure uploading file", e);
}
finally {
Closeables.close(is); // closes silently, but logs errors
}
}
private boolean moveToSentDirectory(File from) {
File to = new File(this.workDirectory + File.separatorChar + this.sentDirectory + File.separatorChar + from.getName());
try {
this.logger.debug("Moving file [from={},to={}]", from, to);
Files.createParentDirs(to);
Files.move(from, to); // this throws an IOException
return true;
}
catch (IOException ioe) {
this.logger.error("Failure moving file [from=" + from + ",to=" + to + "]", ioe);
}
return false;
}

The code works fine on Linux, but on Windows it complains that the "from" file cannot be deleted, when the file is supposed to be moved using the Google Guava Files.move(File from, File to) method. There is a very subtle thing one has to do to get it to work on Windows. What is it?

Post your answers in the comments and then I will let you know after a while :)