Search code examples
javafilenio

java.nio.file.Files move operation


I have used Files.move method in my program as mentioned below.

 public boolean moveAndRenameFile(String targetPath, String newName)
  {
    boolean fileMoved = true;
    try
    {
      Path pathToFile = FileSystems.getDefault().getPath(targetPath);
      Files.move(Paths.get(path), pathToFile.resolve(newName), StandardCopyOption.REPLACE_EXISTING);
    }
    catch (InvalidPathException | IOException e)
    {
      LOGGER.error("File couldn't be moved from {} to target location {}", path, targetPath);
      LOGGER.error(e.getMessage(), e);
      fileMoved = false;
    }
    return fileMoved;
  }

Is it possible, that the file is deleted from original location but not moved to target location if any exception/error occurred in the middle?

I went through following link, but couldn't find answer for this question. https://docs.oracle.com/javase/tutorial/essential/io/move.html


Solution

  • The original (source) file won't get deleted until the process is completed. But an incomplete/corrupted file would be saved in the destination.


    You can confirm this by doing a little test by yourself. Move a file to a removable disk and unplug the removable device before the process ends.