遍历文件夹内的文件(我们到底能走多远系列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 2012-08-18 23:45  每当变幻时  阅读(645)  评论(0编辑  收藏  举报

导航