猿问

java.nio.file.Files 移动操作

我在我的程序中使用了 Files.move 方法,如下所述。


 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;

  }

如果中间发生任何异常/错误,是否有可能从原始位置删除文件但不移动到目标位置?


我浏览了以下链接,但找不到这个问题的答案。 https://docs.oracle.com/javase/tutorial/essential/io/move.html


开满天机
浏览 212回答 2
2回答

繁星淼淼

在该过程完成之前,原始(源)文件不会被删除。但是不完整/损坏的文件将保存在目标中。您可以通过自己做一个小测试来确认这一点。将文件移动到可移动磁盘并在该过程结束之前拔下可移动设备。

www说

对于同一个存储提供者,它使用原生移动。否则它会做一个copyToForeignTarget(...); Files.delete(source);所以不会有问题。
随时随地看视频慕课网APP

相关分类

Java
我要回答