akshay
akshay

Reputation: 5285

can file.renameTo replace a existing file?

// File (or directory) to be moved
File file = new File("filename");

// Destination directory
File dir = new File("directoryname");

// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
    // File was not successfully moved
    //can it be because file with file name already exists in destination?
}

If the file with name 'filename' already exists in the destination will it be replaced with a new one?

Upvotes: 12

Views: 18280

Answers (3)

stacker
stacker

Reputation: 68972

From Javadoc:

The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists.

I tested the following code:

It works the first time, second time it fails as expected. To move a file you should delete or rename the destination if required.

public class Test {
    public static void main(String[] args) throws IOException {
        File file = new File( "c:\\filename" );
        file.createNewFile();
        File dir = new File( "c:\\temp" );
        boolean success = file.renameTo( new File( dir, file.getName() ) );
        if ( !success ) {
            System.err.println( "succ:" + success );
        }
    }
}

Upvotes: 3

mnicky
mnicky

Reputation: 1388

According to Javadoc:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

Upvotes: 12

Rostislav Matl
Rostislav Matl

Reputation: 4543

As it is system dependent you should not expect it to behave this or other way. Check it and implement your own logic.

Upvotes: 0

Related Questions