Reliable File.renameTo() alternative on Windows? Reliable File.renameTo() alternative on Windows? windows windows

Reliable File.renameTo() alternative on Windows?


See also the Files.move() method in JDK 7.

An example:

String fileName = "MyFile.txt";try {    Files.move(new File(fileName).toPath(), new File(fileName).toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);} catch (IOException ex) {    Logger.getLogger(SomeClass.class.getName()).log(Level.SEVERE, null, ex);}


For what it's worth, some further notions:

  1. On Windows, renameTo() seems to fail if the target directory exists, even if it's empty. This surprised me, as I had tried on Linux, where renameTo() succeeded if target existed, as long as it was empty.

    (Obviously I shouldn't have assumed this kind of thing works the same across platforms; this is exactly what the Javadoc warns about.)

  2. If you suspect there may be some lingering file locks, waiting a little before the move/rename might help. (In one point in our installer/upgrader we added a "sleep" action and an indeterminate progress bar for some 10 seconds, because there might be a service hanging on to some files). Perhaps even do a simple retry mechanism that tries renameTo(), and then waits for a period (which maybe increases gradually), until the operation succeeds or some timeout is reached.

In my case, most problems seem to have been solved by taking both of the above into account, so we won't need to do a native kernel call, or some such thing, after all.


The original post requested "an alternative, reliable approach to do a quick move/rename with Java on Windows, either with plain JDK or some external library."

Another option not mentioned yet here is v1.3.2 or later of the apache.commons.io library, which includes FileUtils.moveFile().

It throws an IOException instead of returning boolean false upon error.

See also big lep's response in this other thread.