My Java program needs to synchronously move a file on a server, ie. within the same set of local file systems. The obvious solution is to use Files.move(). However, I've read that in some cases, eg. across file systems, a move will fall-back to copy-and-delete. As I'm moving large files I'd like to be able to report progress to the user if a copy take places (as there will be a noticeable delay).
However, I cannot find a simple way to do this with the Java API. I could potentially write my own copy routine that reports progress, but then I would need to know if the move is going to result in a copy.
One possibility seems to be something like:
try {
Files.move(src, dest, CopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
// Perform a copy instead (and report progress)
}
However it's not clear to me from the Java doco if this would be correct in all cases. Is this indeed a correct solution? If not, is there another way?
Yes, your solution is fine.
Although it is not actually the filesystems that change move into copy. Atomic operation is an operation that takes place on same physical device, meaning that Files.move(..,..,CopyOption.ATOMIC_MOVE)
will always succeed unless you copy to another drive OR if filesystem or OS for some reason does not support atomic operations. Meaning you can have /dev/sda/
and /dev/sdb
, both with ext4
filesystem and you CANNOT perform atomic move from one to another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With