What is the proper way to rename a file in Java?

What I mean under ‘proper’ file renaming:

  1. It should work on different platforms.

  2. It should handle in some way cases when:

    1. the file is locked
    2. a file with ‘new’ name already exists
    3. there’s not enough free space on the disk to complete the operation.

Are there any common solutions/libs/strategies?

Answer

As described in the javadoc:

Renames the file denoted by this abstract pathname. 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.

Here’s an example:

// The File (or directory) with the old name
File oldFile = new File("old.txt");

// The File (or directory) with the new name
File newFile = new File("new.txt");

// Rename file (or directory)
boolean success = oldFile.renameTo(newFile);
if (!success) {
    // File was not successfully renamed
}

My advice would be to check the success boolean and use the standard approach defined in the API.

Leave a Reply

Your email address will not be published. Required fields are marked *