1. 读取基础属性:BasicFileAttributes
当我们谈到文件或文件夹时,关注的不仅是名称或大小。每个文件都有一份“身份证”——一组属性,其中包含:
- 创建时间
- 最后修改时间
- 最后访问时间
- 大小
- 访问权限(谁可以读取、写入、执行)
- 所有者信息(在 Unix 上)
- “隐藏”“只读”等标志
在 Java 中,包 java.nio.file.attribute 提供了便捷而强大的 API 来处理这些属性。无需编写与平台相关的代码:标准库已提供所需的一切。
首先——导入所需的类:
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;
如何获取文件的基础属性?
使用 Files.readAttributes 方法:
Path path = Paths.get("example.txt");
try {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("创建于:" + attrs.creationTime());
System.out.println("修改于:" + attrs.lastModifiedTime());
System.out.println("最后访问:" + attrs.lastAccessTime());
System.out.println("大小:" + attrs.size());
System.out.println("是否为目录?" + attrs.isDirectory());
System.out.println("是否为常规文件?" + attrs.isRegularFile());
System.out.println("是否为符号链接?" + attrs.isSymbolicLink());
} catch (IOException e) {
System.out.println("读取属性时出错:" + e.getMessage());
}
把自己想象成一名检查员,去检查一套公寓。你不仅要看门是否存在(文件是否存在),还会询问住户:“这栋楼何时建成?最近一次装修是什么时候?谁是房主?”。
BasicFileAttributes 属性速览
| 属性 | 返回什么? |
|---|---|
|
文件/文件夹的创建日期和时间 |
|
最后修改的日期和时间 |
|
最后访问的日期和时间 |
|
文件大小(字节) |
|
是否为目录? |
|
是否为常规文件? |
|
是否为符号链接? |
2. 扩展属性:POSIX 与 DOS
POSIX 属性(Linux、macOS 及其他类 Unix 系统)
在 Unix 系统上,可以获取更丰富的信息:权限、所有者、用户组。
try {
PosixFileAttributes posixAttrs = Files.readAttributes(path, PosixFileAttributes.class);
System.out.println("所有者:" + posixAttrs.owner().getName());
System.out.println("用户组:" + posixAttrs.group().getName());
System.out.println("权限:" + PosixFilePermissions.toString(posixAttrs.permissions()));
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 POSIX 属性。");
} catch (IOException e) {
System.out.println("读取 POSIX 属性时出错:" + e.getMessage());
}
注意:在 Windows 上,此代码会抛出 UnsupportedOperationException——这是正常现象。
DOS 属性(Windows)
在 Windows 上,可以处理“只读”“隐藏”“存档”“系统”等标志:
try {
DosFileAttributes dosAttrs = Files.readAttributes(path, DosFileAttributes.class);
System.out.println("隐藏:" + dosAttrs.isHidden());
System.out.println("只读:" + dosAttrs.isReadOnly());
System.out.println("系统:" + dosAttrs.isSystem());
System.out.println("存档:" + dosAttrs.isArchive());
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 DOS 属性。");
} catch (IOException e) {
System.out.println("读取 DOS 属性时出错:" + e.getMessage());
}
3. 修改文件属性
读取“身份证”是一回事,改动“生日”或“姓氏”则是另一回事!在 Java 中,我们可以修改文件属性(当然需要相应权限)。
修改最后修改时间
import java.nio.file.attribute.FileTime;
Path file = Paths.get("example.txt");
try {
FileTime newTime = FileTime.fromMillis(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // 减去 1 天
Files.setLastModifiedTime(file, newTime);
System.out.println("最后修改时间已更新!");
} catch (IOException e) {
System.out.println("修改时间时出错:" + e.getMessage());
}
修改访问权限(POSIX)
仅适用于 Unix 系统!例如,让文件对所有人可执行:
try {
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-xr-x");
Files.setPosixFilePermissions(file, perms);
System.out.println("权限已更新!");
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 POSIX 权限。");
} catch (IOException e) {
System.out.println("修改权限时出错:" + e.getMessage());
}
关于字符串 "rwxr-xr-x":
- r — read(读取)
- w — write(写入)
- x — execute(执行)
- 前三个字符属于所有者,接下来的三个属于用户组,最后三个属于其他用户。
修改隐藏/只读状态(DOS 属性,Windows)
将文件设为隐藏:
try {
Files.setAttribute(file, "dos:hidden", true);
System.out.println("文件已变为隐藏(Windows)!");
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 DOS 属性。");
} catch (IOException e) {
System.out.println("修改属性时出错:" + e.getMessage());
}
将文件设为“只读”:
try {
Files.setAttribute(file, "dos:readonly", true);
System.out.println("文件现为只读(Windows)!");
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 DOS 属性。");
} catch (IOException e) {
System.out.println("修改属性时出错:" + e.getMessage());
}
4. 检查访问权限
有时需要快速检查文件是否可读、可写或可执行:
Path file = Paths.get("example.txt");
System.out.println("可读:" + Files.isReadable(file));
System.out.println("可写:" + Files.isWritable(file));
System.out.println("可执行:" + Files.isExecutable(file));
在所有平台上用法相同,但实际行为取决于操作系统和安全设置。
5. 实战:输出文件的详细信息
编写一个小程序:给定文件路径,尽可能多地显示信息,并尝试修改部分属性。
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;
import java.io.IOException;
public class FileAttributesDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("example.txt");
if (!Files.exists(path)) {
System.out.println("未找到文件!");
return;
}
// 基础属性
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("名称:" + path.getFileName());
System.out.println("路径:" + path.toAbsolutePath());
System.out.println("大小:" + attrs.size() + " 字节");
System.out.println("创建于:" + attrs.creationTime());
System.out.println("修改于:" + attrs.lastModifiedTime());
System.out.println("最后访问:" + attrs.lastAccessTime());
System.out.println("是否为目录?" + attrs.isDirectory());
System.out.println("是否为常规文件?" + attrs.isRegularFile());
// 检查访问权限
System.out.println("可读:" + Files.isReadable(path));
System.out.println("可写:" + Files.isWritable(path));
System.out.println("可执行:" + Files.isExecutable(path));
// 尝试更新最后修改时间
FileTime now = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, now);
System.out.println("最后修改时间已更新!");
// 尝试将文件设为隐藏(如果支持)
try {
Files.setAttribute(path, "dos:hidden", true);
System.out.println("文件已设为隐藏(如果操作系统支持)。");
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持隐藏文件。");
}
// 尝试输出 POSIX 权限(如果支持)
try {
PosixFileAttributes posixAttrs = Files.readAttributes(path, PosixFileAttributes.class);
System.out.println("所有者:" + posixAttrs.owner().getName());
System.out.println("权限:" + PosixFilePermissions.toString(posixAttrs.permissions()));
} catch (UnsupportedOperationException e) {
System.out.println("此操作系统不支持 POSIX 属性。");
}
}
}
6. 实用细节
跨平台差异与建议
- 并非所有属性在所有操作系统上都可用! Windows 没有 POSIX 权限,Linux 没有 DOS 属性.
- 务必使用 try-catch! 方法可能抛出 UnsupportedOperationException 或 IOException。
- 权限并不总是只有“rwx”! 在 Windows 上权限模型不同,“只读”可能由操作系统的安全策略设置。
- “隐藏文件”是相对概念。 在 Unix 中,若文件名以点开头(.hidden)则被视为隐藏;在 Windows 中,需要设置属性 dos:hidden。
表格:不同系统可用的属性
| 属性 | Windows(dos:*) | Linux/macOS(posix:*) |
|---|---|---|
| 创建时间 | + | + |
| 最后修改时间 | + | + |
| 最后访问时间 | + | + |
| 隐藏文件 | + | 仅文件名以点开头 |
| 只读 | + | + |
| 权限(rwx) | - | + |
| 所有者、用户组 | - | + |
| 存档、系统 | + | - |
7. 处理文件属性时的常见错误
错误 1:在 Windows 上尝试读取或修改 POSIX 属性。 在 Windows 上会得到 UnsupportedOperationException。编写跨平台代码时务必处理该异常。
错误 2:修改被其他进程打开的文件的最后修改时间。 在某些系统上,文件可能被锁定,操作会失败。
错误 3:期望“隐藏文件”在所有操作系统上表现一致。 在 Unix 中,文件名以点开头(.gitignore)即为隐藏;而在 Windows 中,需要设置属性 dos:hidden。不要混淆这两种方式。
错误 4:忽视在操作前检查文件是否存在。 如果文件不存在,在获取或修改属性时会抛出 NoSuchFileException。
错误 5:未检查访问权限。 如果用户没有修改属性的权限,操作会失败。修改前请先检查 Files.isWritable(path)。
GO TO FULL VERSION