Search code examples
javanio

Check if file move succeeded by Files from java nio


I need to move files from one location to another on the unix box and I am using the below code to perform the move:

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

Once the file is in the destination, I need to do some additional processing. I am making the code sleep for 10 sec so that before the processing starts, the move should have already been completed. Is there any better way to make sure the move succeeded before the rest of the code runs?


Solution

  • Do a search before posting:

    Sources:

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

      If your extra paranoid try printing out everything:

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