Reputation: 55800
I have the following snippet of java code:
File directoryToMoveTo = new File(file.getParent()+"_TEMP");
boolean success = file.renameTo(new File(directoryToMoveTo,file.getName()));
if (!success){
logger.warn("Failed to move [%s] to temp Directory.");
}
file is passed in as an argument to the method and is one of an array of files obtained like this:
File[] files = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
logger.debug(String.format("Testing file [%s]",name));
boolean passed = name.endsWith(getFileDescription().getFilePattern());
logger.debug(String.format("Passed [%s]",passed));
return passed;
}
});
Why would success by false in the first snippet?
I tried this code in isolation on a different file and it seems to work.
Upvotes: 3
Views: 6922
Reputation: 75679
The file may be still open, even though you closed it: https://bugs.java.com/bugdatabase/view_bug?bug_id=6266377
Upvotes: 1
Reputation: 55800
I found the problem. It was because the directory I was copying to didn't exist.
surrounding with this if statement worked:
if (directoryToMoveTo.exists() || directoryToMoveTo.mkdir()){ }
Upvotes: 3
Reputation: 16246
To find the exact reason why it is not working you could System.out.println
these paths and try to move them from OS level. That would give the good indication why is it not working.
Upvotes: 0
Reputation: 54101
I can think of:
Upvotes: 1
Reputation: 6390
Original doesn't exist? Already a file at the destination path? Destinatination path doesn't exist? Source file read only?
Just a few ideas
Upvotes: 1
Reputation: 4356
Not to forget you might not be allowed to write/change/rename a file.
Hardly ever a problem in windows, but common in Unix environments.
Upvotes: 0
Reputation: 1503519
Obvious situations:
I'd expect those to at least potentially fail (the JavaDoc explicitly says that a lot of this behaviour is OS-dependent) - have you tried them?
Upvotes: 6