如何在Java中使用FileUtils移动文件?


使用File类

java.io包中的名为File的类表示系统中的文件或目录(路径名)。此类提供各种方法来对文件/目录执行各种操作。

此类提供各种方法来操作文件,File类的rename()方法接受一个表示目标文件的字符串,并将当前文件的抽象文件路径重命名为给定的路径。

此方法实际上将文件从源路径移动到目标路径。

示例

 在线演示

import java.io.File;
public class MovingFile {
   public static void main(String args[]) {
      //Creating a source file object
      File source = new File("D:\source\sample.txt");
      //Creating a destination file object
      File dest = new File("E:\dest\sample.txt");
      //Renaming the file
      boolean bool = source.renameTo(dest);
      if(bool) {
         System.out.println("File moved successfully ........");
      }
      else {
         System.out.println("Unable to move the file ........");
      }
   }
}

输出

File moved successfully . . . . . . .

使用Files类

从Java 7开始引入了Files类,它包含对文件、目录或其他类型的文件进行操作的(静态)方法。

此类的move方法分别接受两个路径对象source和destination(以及一个可变参数来指定移动选项),并将source路径表示的文件移动到destination路径。

示例

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MovingFile {
   public static void main(String args[]) throws Exception {
      //Creating a source Path object
      Path source = Paths.get("D:\source\sample.txt");
      //Creating a destination Path object
      Path dest = Paths.get("E:\dest\sample.txt");
      //copying the file
      Files.move(source, dest);
      System.out.println("File moved successfully ........");
   }
}

输出

File moved successfully . . . . . . .

更新于:2019年9月11日

625 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.