我在程序中使用了 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
最佳答案
在该过程完成之前,原始(源)文件不会被删除。但不完整/损坏的文件将保存在目标位置。
您可以通过自己做一个小测试来确认这一点。将文件移至可移动磁盘并在进程结束之前拔下可移动设备。
关于java.nio.file.文件移动操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54347494/