是否可以使用 Java 中的 File 对象来更改目录?
File 类
java.io 包中名为 File 的类表示系统中的文件或目录(路径名称)。此类提供了多种方法,用于对文件/目录执行各种操作。
此类提供了用于操作文件的方法,**File** 类的 renameTo() 方法接受一个表示目标文件并将其当前文件的抽象文件路径重命名为给定文件路径的字符串。
此方法实际上将文件从源路径移动到目标路径。
示例
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 类以来,它包含(静态)方法,用于对文件、目录或其他类型的文件进行操作。
此类的移动方法分别接受两个路径对象(源和目标)(以及一个可变参数来指定移动选项),并将源路径表示的文件移动到目标路径。
示例
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 . . . . . . .
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP