1 概述
File 对象是 Java 提供来操作文件和目录的对象。
1.1 使用
/*
通过传入绝对路径创建File对象
*/File file = new File("F:\\download\\file.txt");
/*
通过传入相对路径创建File对象
*/File file1 = new File("file.text");
- 绝对路径:以根目录开始的路径;
- 相对路径:当前路径加相对路径就是绝对路径;
win 中已 \ 作为文件分割符,linux 中以 / 作为文件分割符,JAVA 中 \\ 表示一个 \;
. 表示当前路径, .. 表示上级路径。
1.2 获取路径的方法
| 方法 | 作用 |
|---|
| public String getPath() | 获取构造方法传入的路径 |
| public String getAbsolutePath() | 获取绝对路径 |
| public String getCanonicalPath() | 获取规范路径名称 |
规范路径:与绝对路径相似,但会根据不同操作系统切换文件分割符,会将相对路径的 ., .. 转换为绝对路径。
File 提供了 separator 常量自动获取当前操作系统的分隔符。
File file2 = new File("F:"+File.separator+"download"+File.separator+"file.txt");
2 文件和目录
File 对象根据构造方法传入的路径不同可以表示文件也可以表示目录,且即使传入的路径不存在也不回报错,只有在使用时才会抛出异常。
2.1 常见方法
| 方案 | 描述 |
|---|
| public boolean exists() | 文件是否存在 |
| public boolean isFile() | 判断传参是否为文件 |
| public boolean isDirectory() | 判断传参是否文件夹 |
| public boolean canRead() | 是否可读 |
| public boolean canWrite() | 是否可写入 |
| public boolean canExecute() | 是否可执行 |
| public long length() | 获取文件字节大小 |
3 创建和删除
构造方法传入路径,根据路径创建和删除对应文件。
3.1 常见方法
| 方法 | 描述 |
|---|
| public boolean createNewFile() | 创建文件 |
| public boolean delete() | 删除文件 |
| public static File createTempFile | 创建临时文件 |
| public boolean mkdir() | 创建目录 |
| public boolean mkdirs() | 创建目录及父级目录 |
4 遍历文件和目录
当需要获取某个文件夹之下的文件及文件夹,需要对传入文件夹进行遍历操作。
4.1 常见方案
| 方案 | 目录 |
|---|
| public String[] list() | 获取目录下的文件及目录 |
| public File[] listFiles() | 获取目录下的文件及目录且过滤不需要的目录 |
| public boolean delete() | 删除文件夹,且文件夹必须为空 |
5 Path
作用于 File 对象类似,用于表达文件系统中的路径。
5.1 使用
| 方法 | 描述 | 示例 |
|---|
Paths.get(String) | 通过路径字符串创建(支持多参数拼接) | Path p = Paths.get("a", "b") |
Paths.get(URI) | 从URI创建 | Path p = Paths.get(uri) |
File.toPath() | 将传统File对象转换为Path | Path p = new File("test").toPath() |
5.2 常见方法
| 方法 | 功能 | 示例 |
|---|
getFileName() | 获取路径的文件名或最后一个目录名 | path.getFileName()→ file.txt |
getParent() | 获取父路径 | path.getParent()→ /usr/local |
getRoot() | 获取根路径(如/或C:) | path.getRoot()→ / |
resolve(Path other) | 拼接路径(若other是绝对路径则返回other) | path.resolve("docs")→ 合并路径 |
relativize(Path other) | 计算相对路径(需两路径有共同前缀) | path1.relativize(path2)→ ../b |
5.3 与 File 对象配合使用
// 检查文件是否存在
boolean exists = Files.exists(path);
// 创建目录(递归创建父目录)
Files.createDirectories(path.getParent());
// 复制文件
Files.copy(path, targetPath, StandardCopyOption.REPLACE_EXISTING);
// 读取文件内容
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
5.4 与 File 对比
| 特性 | java.io.File | java.nio.file.Path |
|---|
| 路径操作 | 方法分散(如getAbsolutePath()) | 方法集中(如resolve()、relativize()) |
| 符号链接支持 | 有限 | 完整支持(Files.readSymbolicLink()) |
| 异常处理 | 返回错误码 | 抛出IOException,更直观 |
| 性能 | 较低效 | 高效(尤其适合批量操作) |