Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a file rename fail in java

Tags:

java

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.

like image 468
Omar Kooheji Avatar asked Jan 27 '26 21:01

Omar Kooheji


1 Answers

Obvious situations:

  • the target file already exists
  • the target directory doesn't exist
  • the target directory is on a different file system
  • the target directory is read-only (or at least, the current user doesn't have write access)

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?

like image 151
Jon Skeet Avatar answered Jan 29 '26 10:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!