368. Java IO API - 基本文件属性

文章目录

368. Java IO API - 基本文件属性

在文件操作中,经常需要读取文件的基本属性,例如创建时间、最后修改时间、文件大小等。Java 提供了 Files.readAttributes() 方法,允许你一次性读取多个基本文件属性,这样可以有效提高性能,避免多次访问文件系统。

🛠️ 使用 Files.readAttributes() 读取基本文件属性

Files.readAttributes() 方法返回 BasicFileAttributes 类的实例,该类包含了多个常用的文件属性,如:

  • creationTime:文件的创建时间。
  • lastModifiedTime:文件的最后修改时间。
  • lastAccessTime:文件的最后访问时间。
  • isDirectory():文件是否为目录。
  • isRegularFile():文件是否为常规文件。
  • isSymbolicLink():文件是否为符号链接。
  • size():文件的大小(以字节为单位)。

使用 Files.readAttributes() 方法一次性获取这些属性比逐一获取每个属性要高效得多,尤其是在需要处理大量文件时。

示例:读取基本文件属性
java 复制代码
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;

public class BasicFileAttributesDemo {
    public static void main(String[] args) {
        Path file = Paths.get("example.txt");

        try {
            BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
            
            // 输出文件的时间戳和基本属性
            System.out.println("创建时间: " + attr.creationTime());
            System.out.println("最后访问时间: " + attr.lastAccessTime());
            System.out.println("最后修改时间: " + attr.lastModifiedTime());
            
            System.out.println("是否是目录: " + attr.isDirectory());
            System.out.println("是否是常规文件: " + attr.isRegularFile());
            System.out.println("是否是符号链接: " + attr.isSymbolicLink());
            System.out.println("文件大小: " + attr.size() + " 字节");
        } catch (IOException e) {
            System.err.println("读取文件属性失败: " + e.getMessage());
        }
    }
}
  • BasicFileAttributes 类是一个包含文件基本属性的接口,常用的属性如创建时间、最后访问时间、文件大小等,可以通过 Files.readAttributes() 方法一次性读取。
  • 注意:creationTime、lastModifiedTime 和 lastAccessTime 这三个时间戳在某些文件系统实现中可能不被支持,返回的值会是实现特定的默认值。

⏳ 设置时间戳

在某些场景下,我们可能需要修改文件的时间戳,比如更新文件的最后修改时间。可以通过 Files.setLastModifiedTime() 方法来实现。

示例:设置文件的最后修改时间
java 复制代码
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;

public class SetFileTimeDemo {
    public static void main(String[] args) {
        Path file = Paths.get("example.txt");

        try {
            // 获取当前时间并转换为 FileTime
            long currentTime = System.currentTimeMillis();
            FileTime ft = FileTime.fromMillis(currentTime);
            
            // 设置文件的最后修改时间
            Files.setLastModifiedTime(file, ft);
            System.out.println("文件的最后修改时间已更新!");
        } catch (IOException e) {
            System.err.println("设置文件修改时间失败: " + e.getMessage());
        }
    }
}
  • FileTime.fromMillis(long) 方法允许你将当前的时间戳(以毫秒为单位)转换为 FileTime 对象,然后通过 Files.setLastModifiedTime() 方法将其设置到文件上。

⚠️ 关注符号链接

使用 Files.readAttributes() 方法时,若文件路径指向符号链接,默认会返回符号链接的属性。如果你不希望访问符号链接的目标文件,可以使用 LinkOption.NOFOLLOW_LINKS 参数来避免跟随符号链接。

示例:避免跟随符号链接
java 复制代码
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;

public class AvoidSymbolicLinkFollow {
    public static void main(String[] args) {
        Path file = Paths.get("symlink.txt");

        try {
            BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            
            // 输出符号链接的属性
            System.out.println("是否是符号链接: " + attr.isSymbolicLink());
        } catch (IOException e) {
            System.err.println("读取符号链接属性失败: " + e.getMessage());
        }
    }
}
  • LinkOption.NOFOLLOW_LINKS 参数确保读取的是符号链接本身的属性,而不是它指向的目标文件的属性。

🏷️ fileKey() 方法

除了读取常见的属性,BasicFileAttributes 还提供了 fileKey() 方法,用于获取文件的唯一标识符。这个标识符是与文件系统相关的,可以用来唯一标识文件。然而,并不是所有的文件系统都支持文件键,如果不可用,fileKey() 将返回 null。

示例:获取文件的唯一标识符
java 复制代码
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;

public class FileKeyDemo {
    public static void main(String[] args) {
        Path file = Paths.get("example.txt");

        try {
            BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
            Object fileKey = attr.fileKey();
            System.out.println("文件的唯一标识符: " + (fileKey != null ? fileKey : "无文件键"));
        } catch (IOException e) {
            System.err.println("获取文件标识符失败: " + e.getMessage());
        }
    }
}
  • attr.fileKey() 方法返回文件的唯一标识符,若文件系统不支持文件键,则返回 null。

📝 总结

  • Files.readAttributes() 方法是高效读取文件基本属性的工具,可以批量获取文件的创建时间、修改时间、大小等常见属性。
  • 时间戳(如创建时间、最后修改时间)可能会受到文件系统的支持限制。
  • 符号链接 的处理可以通过 LinkOption.NOFOLLOW_LINKS 来避免跟随符号链接。
  • fileKey() 方法提供了一个文件的唯一标识符,但并非所有文件系统都支持此功能。

通过这些方法,Java 提供了灵活高效的工具来管理文件属性,可以大大提高文件操作的性能和可用性。

相关推荐
大侠归来5 分钟前
C语言与C++在基础语法上的区别
java·c语言·c++
huisheng_qaq12 分钟前
【Python基础篇-09】深入理解python的闭包与装饰器
python·闭包
小宋102129 分钟前
SQL + RAG 混合问答实战:结构化指标与文档证据如何统一路由
java·jvm·人工智能·sql
bro_Java66635 分钟前
链表进阶2:双向链表的构建
java·数据结构·链表
DianSan_ERP1 小时前
多平台订单自动下载与回传的技术实现:从消息推送到状态闭环引言
java·linux·服务器·前端·网络·架构·自动化
Joe_Wang51 小时前
【从0到1学习JVM · 13】点进JDK源码只有一个分号?搞懂本地方法栈与JNI机制
java·jvm·学习·本地方法栈
编码者卢布1 小时前
【App Service 】WebJobs 多实例实验:谁在运行,什么时候运行?
开发语言·python
kaixin_learn_qt_ing1 小时前
Qt抽屉窗体实现demo
开发语言·qt
quantdash_cc1 小时前
Python 获取实时行情后如何进行批量筛选?从全市场快照到策略候选池
开发语言·python·数据分析·量化交易·股票数据·quantdash
AI 算法大模型备案~当当1 小时前
各地备案数量怎么看:一份属地公告的认读与台账方法
java·数据库·人工智能