Moving a file from one directory to another using Java

Java 8Object Oriented ProgrammingProgramming

We can use Files.move() API to move file from one directory to another. Following is the syntax of the move method.

public static Path move(Path source,Path target,CopyOption... options) throws IOException

Where

  • source − Source path of file to be moved

  • target − Target path of file to be moved

  • options − options like REPLACE_EXISTING, ATOMIC_MOVE

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Tester {
   public static void main(String[] args) {
      //move file from D:/temp/test.txt to D:/temp1/test.txt
      //make sure that temp1 folder exists
      moveFile("D:/temp/test.txt", "D:/temp1/test.txt");
   }
   private static void moveFile(String src, String dest ) {
      Path result = null;
      try {
         result = Files.move(Paths.get(src), Paths.get(dest));
      } catch (IOException e) {
         System.out.println("Exception while moving file: " + e.getMessage());
      }
      if(result != null) {
         System.out.println("File moved successfully.");
      }else{
         System.out.println("File movement failed.");
      }
   }
}

Output

File moved successfully.
raja
Published on 01-Nov-2018 15:14:37
Advertisements