1

I'm looking for the safest way to move a directory in Java. My code right now is basically

Path destPath = Paths.get(parentPath.toString().replace("service", "input"));
org.apache.commons.io.FileUtils.deleteQuietly(destPath.toFile());
org.apache.commons.io.FileUtils.moveDirectory(parentPath.toFile(), destPath.toFile());

Where parentPath is something like /dir/service/ and thus destPath is /dir/input/.

My problem is that while this approach works 99% of the time, in some cases it fails and deletes the files on the directory it was supposed to move. (It launches an IOException on the moveDirectory function claiming that it was not possible to delete the directory).

I need a way to make sure this problem is not going to happen (or at least my files would be safe), given that I cannot afford to lose this files.

I'm open to any new approaches too, I just need it to be safe and not too slow (given that my method is going to work with a high number of directories all the time).

  • I appreciate the accept! Please let me know if there is anything I can do to make my answer also upvote worthy :-) – GhostCat Feb 22 '18 at 05:17

1 Answers1

1

The "safest" solution might be to first copy one file, to then check if the copy is identical to the source - to then delete the source file. And if something goes wrong you just stop right there.

The downside is that you might have to implement this manually. But if data integrity is your primary requirement then you should look at things from the single file point of view.

GhostCat
  • 137,827
  • 25
  • 176
  • 248