检查java nio中的文件是否成功移动文件

时间:2016-03-18 18:56:04

标签: java nio

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

s/\s+/ /g;

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

1 个答案:

答案 0 :(得分:0)

在发布前进行搜索:

来源:

  • 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();
        }