如何使用Java获取文件夹中修改时间超2小时的各文件最后修改时间戳
Java 遍历文件夹筛选超时修改文件实现方案
核心依赖说明
使用JDK 7及以上版本内置的NIO.2 API实现,无需引入第三方依赖,相比传统java.io.File类遍历效率更高,属性读取更便捷。
实现步骤
- 计算时间阈值:当前时间减去2小时对应的时间戳,作为筛选的边界值
- 调用
Files.walk遍历目标文件夹,可自行配置是否递归遍历子目录 - 读取每个文件的
lastModifiedTime属性,和阈值做对比 - 收集所有符合条件的文件路径及对应的最后修改时间戳
完整代码示例
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; import java.util.HashMap; import java.util.Map; import java.time.Instant; public class ExpiredFileScanner { public static void main(String[] args) { // 替换为你要遍历的目标文件夹路径 String targetDirPath = "/path/to/your/target/directory"; // 2小时对应的毫秒阈值 long expireThreshold = Instant.now().toEpochMilli() - 7200000; Map<Path, Long> matchedFiles = scanExpiredFiles(Paths.get(targetDirPath), expireThreshold, true); // 输出结果 matchedFiles.forEach((filePath, modifiedTime) -> { System.out.printf("文件路径:%s,最后修改时间戳:%d%n", filePath, modifiedTime); }); } /** * 扫描最后修改时间早于指定阈值的文件 * @param targetDir 目标扫描目录 * @param expireThreshold 时间阈值(毫秒级时间戳),小于该值的文件会被筛选出来 * @param recursive 是否递归遍历子目录 * @return key为文件路径,value为对应最后修改时间戳的Map */ public static Map<Path, Long> scanExpiredFiles(Path targetDir, long expireThreshold, boolean recursive) { Map<Path, Long> result = new HashMap<>(); int maxDepth = recursive ? Integer.MAX_VALUE : 1; try { Files.walk(targetDir, maxDepth) // 只筛选普通文件,跳过目录、符号链接等 .filter(Files::isRegularFile) .forEach(filePath -> { try { BasicFileAttributes attrs = Files.readAttributes(filePath, BasicFileAttributes.class); long lastModified = attrs.lastModifiedTime().toMillis(); if (lastModified < expireThreshold) { result.put(filePath, lastModified); } } catch (IOException e) { // 权限不足、文件被占用等异常处理,可根据业务需求调整 System.err.printf("读取文件属性失败:%s,异常信息:%s%n", filePath, e.getMessage()); } }); } catch (IOException e) { System.err.printf("遍历目录失败:%s,异常信息:%s%n", targetDir, e.getMessage()); } return result; } }
注意事项
- 如果不需要遍历子目录,调用
scanExpiredFiles方法时将第三个参数设为false即可 - 代码中默认跳过了目录和符号链接,如果需要处理符号链接可以修改
filter的判断逻辑 - 异常处理部分可根据业务场景调整,比如直接抛出、存入日志或者忽略
- 时间计算也可以直接用
Instant类做对比,比如attrs.lastModifiedTime().toInstant().isBefore(Instant.now().minus(java.time.Duration.ofHours(2))),写法更直观,无需手动计算毫秒数
内容的提问来源于stack exchange,提问作者unanonymous56
相关产品推荐
相关产品推荐

