java.nio.file.Files 移动操作
java.nio.file.Files move operation
我在我的程序中使用了 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;
}
如果中间发生任何exception/error,是否可以将文件从原始位置删除而不移动到目标位置?
我完成了以下 link,但找不到这个问题的答案。
https://docs.oracle.com/javase/tutorial/essential/io/move.html
在该过程完成之前,原始(源)文件不会被删除。但是 incomplete/corrupted 文件会保存在目的地。
您可以通过自己做一个小测试来确认这一点。将文件移动到可移动磁盘并在进程结束前拔下可移动设备。
对于同一存储提供商,它使用本机移动。
否则它会
copyToForeignTarget(...);
Files.delete(source);
所以不会有问题。
我在我的程序中使用了 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;
}
如果中间发生任何exception/error,是否可以将文件从原始位置删除而不移动到目标位置?
我完成了以下 link,但找不到这个问题的答案。 https://docs.oracle.com/javase/tutorial/essential/io/move.html
在该过程完成之前,原始(源)文件不会被删除。但是 incomplete/corrupted 文件会保存在目的地。
您可以通过自己做一个小测试来确认这一点。将文件移动到可移动磁盘并在进程结束前拔下可移动设备。
对于同一存储提供商,它使用本机移动。
否则它会
copyToForeignTarget(...);
Files.delete(source);
所以不会有问题。