Omar Kooheji
Omar Kooheji

Reputation: 55800

Why would a file rename fail in 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.

Upvotes: 3

Views: 6922

Answers (7)

Sjoerd
Sjoerd

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

Omar Kooheji
Omar Kooheji

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

pajton
pajton

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

Johannes Weiss
Johannes Weiss

Reputation: 54101

I can think of:

  • target directory does not exist
  • not enough access rights (target directory write protected)
  • not enough free space on target directory's data partition
  • ...

Upvotes: 1

Martin Milan
Martin Milan

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

Stroboskop
Stroboskop

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

Jon Skeet
Jon Skeet

Reputation: 1503519

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?

Upvotes: 6

Related Questions