English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Move a file from one directory to another using Java

We can use the Files.move() API to move a file from one directory to another. The 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 the file to be moved

  • Target-target path of the file to be moved

  • options-options, such as 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-
      //Ensure temp1Folder 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));
      }
         System.out.println("Exception while moving file: "); + e.getMessage());
      }
      if(result != null) {
         System.out.println("File has been successfully moved.");
      }
         System.out.println("File move failed.");
      }
   }
}

Output Result

File has been successfully moved.