使用 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+ 浏览量

开启你的职业生涯

完成课程,获得认证

开始吧
广告
© . All rights reserved.