4

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?

Roman
  • 64,384
  • 92
  • 238
  • 332
  • 1
    [Check out the response to a similar question](http://stackoverflow.com/questions/2014586/renaming-a-file-without-using-renameto-java/2835599#2835599) – Jugal Shah Jul 25 '11 at 09:27

2 Answers2

2

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.

carlspring
  • 31,231
  • 29
  • 115
  • 197
1

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...

BegemoT
  • 3,776
  • 1
  • 24
  • 30