Roman
Roman

Reputation: 66196

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?

Upvotes: 4

Views: 1507

Answers (2)

BegemoT
BegemoT

Reputation: 3856

google guava lib contains Files.move(..) mothod, which is confirm some of your requirements -- actually, it tries to move file with File.renameTo(), and, if fails, tries to copy-and-remove-source strategy.

I do not know libs which checks fo free space, since free space can change during move/copy, and the only way to consistently process low space is to have copy/move method to return special error code/exception pointing you to the reason of fail -- which current java File API does not have...

Upvotes: 1

carlspring
carlspring

Reputation: 32657

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.

Upvotes: 2

Related Questions