Java文件遍历

98 阅读1分钟

描述

需求为扫描本地压缩包解压并解析压缩包内文件,压缩包集中放在固定目录。

遍历代码

使用Java的Files工具类,按需加载节省内存使用。

try(Stream<Path> paths = Files.walk(Paths.get("/data/"), 1)){
    paths.filter(path -> path.toString().equalsIgnoreCase(".zip")).forEach(path -> {
        //执行业务逻辑
        Path fileName = path.getFileName();
        System.out.println(fileName);
    });
}catch (Exception e){
    throw new RuntimeException("遍历出错");
}

优化前代码,将所有路径读出来再进行遍历

try(Stream<Path> paths = Files.walk(Paths.get("/data/"), 1)){
    Set<Path> collect = paths.filter(path -> path.toString().equalsIgnoreCase(".zip")).collect(Collectors.toSet());
    for (Path path : collect) {
        //执行业务逻辑
        Path fileName = path.getFileName();
        System.out.println(fileName);
    }
}catch (Exception e){
    throw new RuntimeException("遍历出错");
}