Question

In my Java 7 application I need to move all files and directories in the sourceFolder to another destinationFolder. I do not know whether these two folders are on the same file system or partition, as both can be specified by the user at runtime.

Since the files and directories to move can be quite large (some GB), I was searching for an efficient way of moving them. So they should only be copied if sourceFolder and destinationFolder are not on the same file system. So ideally the move operation on the same file system should rather be a rename operation, if possible.

The application is used on both Windows and Linux systems.

I know about some related Java 7 functionalities, however, they do not allow to move all contents of a folder to somewhere else if it is not empty, which is a requirement in my case. I also found Apache Common's FileUtils class, which looks promising. However, its documentation says one should do a "copy and delete" operation if sourceFolder and destinationFolder are not on the same file system.

So my question is: When I use that FileUtils class, how can I then check the file systems of sourceFolder and destinationFolder in a cross-platform manner?

Was it helpful?

Solution

I assume that you are referring to FileUtils.moveFile().

The moveFile takes care of the case where the source and destination are on different directories. What it does is to try to use File.renameTo, and if that fails, it tries to copy the file. (See the source code.) In short, you don't need to check for yourself ...

But in response to your actual question, neither File or Apache FileUtils provides a way to test if two directories are on the same file system. But (I think) you can do it using Java 7 functionality by something like this:

Path path1 = new File(str1).toPath();
Path path2 = new File(str2).toPath();
if (path1.getFileSystem().equals(path2.getFileSystem()) {
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top