使用 Java 從一個目錄移動檔案到另一個目錄


我們可以使用 Files.move() API 從一個目錄移動檔案到另一個目錄。以下是 move 方法的語法。

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

其中

  • source - 要移動的檔案的源路徑

  • target - 要移動的檔案的目標路徑

  • options - 選項,如 REPLACE_EXISTING、ATOMIC_MOVE

示例

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.");
      }
   }
}

輸出

File moved successfully.

更新於: 2020-06-25

6K+ 瀏覽量

開啟你的職業生涯

完成課程,獲得認證

開始吧
廣告