#前言
在 Java 编程中,文件和目录的操作是非常常见的任务。Java 提供了多个类来处理这些操作,其中 File
、Path
、Paths
和 Files
类尤为重要。
一、java.io.File
类
1.1 概述
java.io.File
类是 Java 早期用于表示文件和目录路径名的抽象类,位于 java.io
包中,自 JDK 1.0 版本就已存在。它主要用于文件和目录的基本操作,如创建、删除、重命名等,以及获取文件和目录的属性信息。虽然 File
类在功能上有一定的局限性,但在简单的文件操作场景中仍然非常实用。
1.2 常用构造方法
File(String pathname)
:通过指定的路径名创建一个File
对象。
File file = new File("C:/temp/test.txt");
File(String parent, String child)
:根据父路径和子路径创建File
对象。
File file = new File("C:/temp", "test.txt");
File(File parent, String child)
:根据父File
对象和子路径创建File
对象。
File parent = new File("C:/temp");
File file = new File(parent, "test.txt");
1.3 常用方法
1.3.1 路径和名称相关
String getName()
:返回文件或目录的名称,即路径名的最后一部分。
File file = new File("C:/temp/test.txt");
System.out.println(file.getName()); // 输出: test.txt
String getPath()
:返回此File
对象的路径名。
File file = new File("C:/temp/test.txt");
System.out.println(file.getPath()); // 输出: C:/temp/test.txt
String getAbsolutePath()
:返回此File
对象的绝对路径名。
File file = new File("test.txt");
System.out.println(file.getAbsolutePath()); // 输出当前工作目录下的绝对路径
File getParentFile()
:返回此File
对象的父目录的File
对象,如果没有父目录则返回null
。
File file = new File("C:/temp/test.txt");
File parent = file.getParentFile();
System.out.println(parent.getPath()); // 输出: C:/temp
1.3.2 存在性和类型判断
boolean exists()
:检查文件或目录是否存在。
File file = new File("test.txt");
if (file.exists()) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
boolean isDirectory()
:判断此File
对象是否表示一个目录。
File dir = new File("C:/temp");
if (dir.isDirectory()) {
System.out.println("这是一个目录");
}
boolean isFile()
:判断此File
对象是否表示一个文件。
File file = new File("C:/temp/test.txt");
if (file.isFile()) {
System.out.println("这是一个文件");
}
1.3.3 创建和删除操作
boolean createNewFile()
:当且仅当指定的文件不存在时,创建一个新的空文件。
File file = new File("newFile.txt");
try {
if (file.createNewFile()) {
System.out.println("文件创建成功");
} else {
System.out.println("文件已存在");
}
} catch (IOException e) {
e.printStackTrace();
}
boolean mkdir()
:创建此File
对象所表示的目录,前提是父目录必须存在。
File dir = new File("C:/temp/newDir");
if (dir.mkdir()) {
System.out.println("目录创建成功");
}
boolean mkdirs()
:创建此File
对象所表示的目录,包括所有必需但不存在的父目录。
File dir = new File("C:/temp/newDir/subDir");
if (dir.mkdirs()) {
System.out.println("多级目录创建成功");
}
boolean delete()
:删除此File
对象所表示的文件或空目录。
File file = new File("test.txt");
if (file.delete()) {
System.out.println("文件删除成功");
}
二、java.nio.file.Path
接口
2.1 概述
java.nio.file.Path
接口是 Java 7 引入的 NIO.2
包中的一部分,位于 java.nio.file
包。它表示文件系统中的路径,提供了比 File
类更强大和灵活的路径操作功能。Path
对象可以用于定位文件或目录,并且支持路径的合并、规范化、相对化等操作。
2.2 创建 Path
对象
通常使用 java.nio.file.Paths
类的 get
方法来创建 Path
对象。
2.3 常用方法
2.3.1 路径元素访问
Path getFileName()
:返回路径的最后一个元素,如果路径表示根目录,则返回null
。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathExample {
public static void main(String[] args) {
Path path = Paths.get("C:/temp/test.txt");
Path fileName = path.getFileName();
System.out.println(fileName); // 输出: test.txt
}
}
Path getParent()
:返回此路径的父路径,如果路径没有父路径则返回null
。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathParentExample {
public static void main(String[] args) {
Path path = Paths.get("C:/temp/test.txt");
Path parent = path.getParent();
System.out.println(parent); // 输出: C:/temp
}
}
Path getRoot()
:返回此路径的根组件,如果路径没有根组件则返回null
。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathRootExample {
public static void main(String[] args) {
Path path = Paths.get("C:/temp/test.txt");
Path root = path.getRoot();
System.out.println(root); // 输出: C:/
}
}
2.3.2 路径操作
Path resolve(Path other)
:将给定的路径与当前路径合并。如果other
是绝对路径,则直接返回other
。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathResolveExample {
public static void main(String[] args) {
Path basePath = Paths.get("C:/temp");
Path subPath = Paths.get("subDir", "test.txt");
Path resolvedPath = basePath.resolve(subPath);
System.out.println(resolvedPath); // 输出: C:/temp/subDir/test.txt
}
}
Path relativize(Path other)
:计算从当前路径到给定路径的相对路径。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathRelativizeExample {
public static void main(String[] args) {
Path basePath = Paths.get("C:/temp");
Path targetPath = Paths.get("C:/temp/subDir/test.txt");
Path relativePath = basePath.relativize(targetPath);
System.out.println(relativePath); // 输出: subDir/test.txt
}
}
Path normalize()
:返回规范化的路径,去除路径中的冗余部分,如.
和..
。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathNormalizeExample {
public static void main(String[] args) {
Path path = Paths.get("C:/temp/./subDir/../test.txt");
Path normalizedPath = path.normalize();
System.out.println(normalizedPath); // 输出: C:/temp/test.txt
}
}
三、java.nio.file.Paths
类
3.1 概述
java.nio.file.Paths
类是一个工具类,位于 java.nio.file
包,主要用于创建 Path
对象。它提供了静态方法 get
来根据不同的参数创建 Path
实例,使用起来非常方便。
3.2 常用方法
static Path get(String first, String... more)
:根据给定的路径元素创建Path
对象。first
是路径的第一个元素,more
是可选的后续路径元素。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathsGetExample {
public static void main(String[] args) {
Path path1 = Paths.get("C:/temp", "test.txt");
System.out.println(path1); // 输出: C:/temp/test.txt
Path path2 = Paths.get("C:", "temp", "test.txt");
System.out.println(path2); // 输出: C:/temp/test.txt
}
}
四、java.nio.file.Files
类
4.1 概述
java.nio.file.Files
类是 Java 7 引入的 NIO.2
包中的一部分,位于 java.nio.file
包。它提供了许多静态方法来操作文件和目录,如文件的读写、复制、移动、删除等,还支持文件属性的获取和设置。Files
类基于 Path
接口进行操作,使得文件操作更加高效和灵活。
4.2 常用方法
4.2.1 文件读写操作
static byte[] readAllBytes(Path path)
:读取指定路径文件的所有字节。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesReadAllBytesExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try {
byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
static List<String> readAllLines(Path path)
:读取指定路径文件的所有行。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FilesReadAllLinesExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
static Path write(Path path, byte[] bytes, OpenOption... options)
:将字节数组写入指定路径的文件。可以通过OpenOption
参数指定写入模式,如StandardOpenOption.CREATE
(如果文件不存在则创建)、StandardOpenOption.APPEND
(追加写入)等。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FilesWriteExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
String content = "Hello, World!";
try {
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.2.2 文件和目录操作
static Path copy(Path source, Path target, CopyOption... options)
:将源文件复制到目标文件。可以通过CopyOption
参数指定复制选项,如StandardCopyOption.REPLACE_EXISTING
(如果目标文件已存在则替换)。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FilesCopyExample {
public static void main(String[] args) {
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
try {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
static Path move(Path source, Path target, CopyOption... options)
:将源文件移动到目标文件,相当于重命名或移动操作。同样可以通过CopyOption
参数指定选项。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FilesMoveExample {
public static void main(String[] args) {
Path source = Paths.get("source.txt");
Path target = Paths.get("newLocation.txt");
try {
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void delete(Path path)
:删除指定路径的文件或空目录,如果文件或目录不存在会抛出NoSuchFileException
。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesDeleteExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
static boolean deleteIfExists(Path path)
:如果指定路径的文件或目录存在,则删除它,并返回true
;如果不存在则返回false
。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesDeleteIfExistsExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try {
if (Files.deleteIfExists(path)) {
System.out.println("文件删除成功");
} else {
System.out.println("文件不存在");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.2.3 文件属性操作
static boolean exists(Path path, LinkOption... options)
:检查指定路径的文件或目录是否存在。可以通过LinkOption
参数指定是否跟随符号链接。
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesExistsExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (Files.exists(path)) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
}
}
static BasicFileAttributes readAttributes(Path path, Class<A> type, LinkOption... options)
:读取指定路径文件的基本属性,如文件大小、创建时间、修改时间等。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class FilesReadAttributesExample {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try {
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("文件大小: " + attributes.size() + " 字节");
System.out.println("创建时间: " + attributes.creationTime());
System.out.println("修改时间: " + attributes.lastModifiedTime());
} catch (IOException e) {
e.printStackTrace();
}
}
}
五、总结
File
类是 Java 早期用于文件和目录操作的类,功能相对基础,适用于简单的文件管理场景。Path
接口、Paths
类和Files
类是 Java 7 引入的NIO.2
包的一部分,提供了更强大、更灵活的文件和目录操作功能,推荐在新的 Java 项目中使用。