如何使用Java获取某文件夹下包含某字符的文件列表且文件按时间排序

有这样一个需求:使用Java语言实现获取某个文件夹下文件名称包含"CDDY"的文件,并按照修改时间升序排列。你可以使用java.nio.file包中的类。以下是一个简单的示例代码,演示如何实现这一功能:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.util.*;

public class FileSearchWithCDDY {

    public static void main(String[] args) {
        Path directory = Paths.get("C:/path/to/your/directory"); // 替换为你的目录路径
        List<Path> filesWithCDDY = getFilesWithCDDY(directory);

        // 按修改时间升序排序
        Collections.sort(filesWithCDDY, Comparator.comparing(path -> {
            try {
                return Files.getLastModifiedTime(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }));

        // 打印结果
        for (Path file : filesWithCDDY) {
            System.out.println(file);
        }
    }

    private static List<Path> getFilesWithCDDY(Path directory) {
        List<Path> filesWithCDDY = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, path -> {
            String fileName = path.getFileName().toString();
            return Files.isRegularFile(path) && fileName.contains("CDDY");
        })) {
            for (Path file : stream) {
                filesWithCDDY.add(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filesWithCDDY;
    }
}

在上面的代码中,getFilesWithCDDY方法使用Files.newDirectoryStream来遍历指定目录下的所有文件,并通过Lambda表达式过滤出文件名包含"CDDY"的文件。然后,Collections.sort方法使用Comparator来比较文件的最后修改时间,并按升序排序这些文件。最后,遍历并打印排序后的文件列表。

请确保将"C:/path/to/your/directory"替换为你想要搜索的实际目录路径。如果目录路径或文件名包含特殊字符或空格,确保在路径字符串中使用正确的转义序列。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值