File类
File
类是 Java 中用于表示文件和目录路径名的类。它的作用主要是通过路径名操作文件和目录,例如创建、删除、重命名等。绝对路径(absolute path)和相对路径(relative path)都是用来指定文件或目录在文件系统中位置的方式。
那么什么是绝对路径,什么是相对路径呢?
绝对路径指的是文件或目录在文件系统中的完整路径,从根目录开始一直到目标文件或目录的路径。在不同的操作系统中表示方式有所不同:
在Unix/Linux系统中,绝对路径从根目录
/
开始,如/home/user/file.txt
。在Windows系统中,绝对路径可能以驱动器名或网络路径开始,如
C:\Users\User\file.txt
或\\server\share\file.txt
。相对路径指的是文件或目录相对于当前工作目录(或另一个已知的基准路径)的路径。它不是完整的路径,而是从一个参考位置出发的路径。相对路径可以是向上或向下的路径,使用相对当前位置的目录层次结构来指定目标文件或目录的位置。例如:
../parent_directory/file.txt
表示向上一级目录,然后进入parent_directory
目录下的file.txt
文件。
subdirectory/file.txt
表示当前目录下的subdirectory
目录中的file.txt
文件。
绝对路径和相对路径的选择取决于需要的准确性和灵活性。绝对路径提供了确切的文件位置,不受当前工作目录的影响,适用于需要确切路径的情况。相对路径则更加灵活,可以根据当前工作环境的变化而适应不同的目录结构,使得项目或脚本更易于移植和管理。
构造方法
File(String pathname)
功能:通过指定路径名创建一个 File
对象。
String filePath = "C:/Users/John/Documents/example.txt";
File file = new File(filePath);
File(String parent, String child)
功能:通过父路径和子路径名创建一个 File
对象。
String parentPath = "C:/Users/John/Documents";
String childPath = "example.txt";
File file = new File(parentPath, childPath);
File(File parent, String child)
功能:通过父 File
对象和子路径名创建一个 File
对象。
File parentDir = new File("C:/Users/John/Documents");
String childPath = "example.txt";
File file = new File(parentDir, childPath);
文件操作方法
boolean createNewFile()
功能:创建一个新文件。
File newFile = new File("C:/Users/John/Documents/newFile.txt");
try {
boolean created = newFile.createNewFile();
if (created) {
System.out.println("文件创建成功");
} else {
System.out.println("文件已存在或创建失败");
}
} catch (IOException e) {
e.printStackTrace();
}
boolean delete()
功能:删除文件或目录。
File fileToDelete = new File("C:/Users/John/Documents/fileToDelete.txt");
boolean deleted = fileToDelete.delete();
if (deleted) {
System.out.println("文件删除成功");
} else {
System.out.println("文件删除失败");
}
boolean renameTo(File dest)
功能:重命名文件或目录。
File oldFile = new File("C:/Users/John/Documents/oldName.txt");
File newFile = new File("C:/Users/John/Documents/newName.txt");
boolean renamed = oldFile.renameTo(newFile);
if (renamed) {
System.out.println("文件重命名成功");
} else {
System.out.println("文件重命名