Java fails in moving (renaming) a file when the resulting file is on another filesystem

filesystems, java, linux

Solution

Java 7 and above

Use `Files.move(Path source, Path target, CopyOption... opts)`.

Note that you must not provide the `ATOMIC_MOVE` option when moving files between file systems.

Java 6 and below

From the docs of `File.renameTo`:

[...] The rename operation might not be able to move a file from one filesystem to another [...]

The obvious workaround would be to copy the file "manually" by opening a new file, write the content to the file, and delete the old file.

You could also try the `FileUtils.moveFile` method from Apache Commons.

Problem

A program we have erred when trying to move files from one directory to another. After much debugging I located the error by writing a small utility program that just moves a file from one directory to another (code below). It turns out that while moving files around on the local filesystem works fine, trying to move a file to another filesystem fails. Why is this? The question might be platform specific - we are running Linux on ext3, if that matters. And the second question; should I have been using something else than the `renameTo()` method of the `File` class? It seems as if this just works on local filesystems. Tests (run as root): ``` touch /tmp/test/afile java FileMover /tmp/test/afile /root/ The file move was successful touch /tmp/test/afile java FileMover /tmp/test/afile /some_other_disk/ The file move was erroneous ``` Code: ``` import java.io.File; public class FileMover { public static void main(String arguments[] ) throws Exception { boolean success; File file = new File(arguments[0]); File destinationDir = new File(arguments[1]); File destinationFile = new File(destinationDir,file.getName() ); success = file.renameTo(destinationFile); System.out.println("The file move was " + (success?"successful":"erroneous")); } } ```

Original source