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

What do I mean by "correct" file renaming:

  • It should work on different platforms.

  • It should handle in some way cases where:

    • file is locked
    • a file named 'new' already exists
    • There is not enough free disk space to complete the operation.

Are there common solutions / libs / strategies?

+4
source share
2 answers

As described in javadoc:

Renames the file indicated by this abstract path. Many aspects of the behavior of this method inherently depend on the platform: the renaming operation cannot move a file from one file system to another, it may not be atomic, and may fail if a file with an abstract destination path name already exists. The return value should always be checked to ensure that the rename operation was successful.

Here is 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 logical success boolean and use the standard approach defined in the API.

+2
source

google guava lib contains Files.move (..) mothod, which confirms some of your requirements - in fact, it tries to move the file from File.renameTo (), and in case of failure it also tries to copy and remove-source.

I do not know libs that checks free space, because free space can change during moving / copying, and the only way to process low space sequentially is to use the copy / move method to return a special error / exception code indicating that you are the reason crashing - which current Java API does not have ...

+1
source

All Articles