遍历文件夹内的文件(我们到底能走多远系列2)

我们到底能走多远系列(2)

遍历指定路径下的文件,文件和文件夹需要区分。

为了把文件名和是否为文件夹记录下来,实现一个model

复制代码
package web.method.file.model;

public class FileModel {
    
    // 是否为文件夹
    private boolean isDirectory;
    
    // 文件名
    private String fileNmae;

    public FileModel(boolean isDirectory, String fileNmae) {
        super();
        this.isDirectory = isDirectory;
        this.fileNmae = fileNmae;
    }

    public boolean isDirectory() {
        return isDirectory;
    }

    public void setDirectory(boolean isDirectory) {
        this.isDirectory = isDirectory;
    }

    public String getFileNmae() {
        return fileNmae;
    }

    public void setFileNmae(String fileNmae) {
        this.fileNmae = fileNmae;
    }
    


}
复制代码

遍历个文件夹java封装了方法供使用:

复制代码
/**
     * 
     * @param String
     *            path 查询文件路径
     * 
     * @return Map<Boolean, String> Boolean->true:文件夹;false:非文件夹,String:文件名/文件夹名
     */
    private List<FileModel> queryAllFileName(String path) {

        // 保证path是"/"或"\\"结尾
        if ((!path.endsWith(File.pathSeparator)) || (!path.endsWith("\\"))) {
            path = path + File.pathSeparator;
        }
        // 查询路径
        File filePath = new File(path);
        // 路径不存在
        if (!filePath.exists()) {
            return null;
        }
        List<FileModel> fileModelList = new ArrayList<FileModel>();
        // 路径不是文件夹
        if (!filePath.isDirectory()) {
            FileModel file = new FileModel(false, path);
            fileModelList.add(file);
            return fileModelList;
        }
        // 取得路劲下文件名或文件夹名
        String[] fileNames = filePath.list();
        for (int i = 0; i < fileNames.length; i++) {
            // 判断是否为文件夹
            if ((new File(path + fileNames[i])).isDirectory()) {
                fileModelList.add(new FileModel(true, fileNames[i]));
            } else {
                fileModelList.add(new FileModel(false, fileNames[i]));
            }
        }

        return fileModelList;
    }
复制代码

posted on   每当变幻时  阅读(651)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

< 2012年8月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

统计

点击右上角即可分享
微信分享提示