【问题标题】:Check if file move succeeded by Files from java nio [closed]检查来自java nio的文件是否成功移动文件[关闭]
【发布时间】:2016-03-18 18:56:04
【问题描述】:

我需要在 unix 机器上将文件从一个位置移动到另一个位置,我正在使用以下代码执行移动:

Path sourcePath = Paths.get(infaFileOut);
Path destinationPath = Paths.get(fileOut);
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);

一旦文件在目的地,我需要做一些额外的处理。我让代码休眠 10 秒,以便在处理开始之前,移动应该已经完成​​。有没有更好的方法来确保在其余代码运行之前移动成功?

【问题讨论】:

  • 我不明白。在Files.move 之后,文件被正确移动或抛出异常。
  • 有几种实现方式。您可以在移动操作后运行检查以检查新文件是否存在于新位置。如果所有文件都已正确移动,则仅将成功值返回给主进程。这样,在完成并验证成功之前,您不会开始第二部分的处理。

标签: java nio


【解决方案1】:

发帖前先搜索一下:

来源:

  • How to move directories using jdk7
  • Moving files from one directory to another with Java NIO

    Path sourcePath = Paths.get(infaFileOut);
    Path destinationPath = Paths.get(fileOut);
    try{
    Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        //this is where the error will be thrown if the file did not move properly 
        //(null pointer etc...), you can place code here to run if there is an error
        e.printStackTrace();
    }
    

    如果您的偏执狂尝试打印所有内容:

       Path sourceDir = Paths.get("c:\\source");
        Path destinationDir = Paths.get("c:\\dest");
    
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)) {
            for (Path path : directoryStream) {
                System.out.println("copying " + path.toString());
                Path d2 = destinationDir.resolve(path.getFileName());
                System.out.println("destination File=" + d2);
                Files.move(path, d2, REPLACE_EXISTING);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2012-04-04
    • 2019-11-14
    相关资源
    最近更新 更多