您的位置:首页 > 其它

如何在遍历目录时指定目录的最大层数

2014-11-12 20:00 531 查看
有时候在查找文件的时候为了提高效率或者出于其它目的要对遍历的目录的层数作下限制,比如在查找自己创建或者下载的文件时,这些文件所在的目录一般都不会太深,

所以在文件比较多的时候,通过限制目录的层次可以极大的提高查找文件的效率,以下为代码:

public static void findFile(String rootDir, String fileName, List<String> fileList,int depth,int maxDepth) {  
    	depth += 1;
        String tempName = null;  
        File baseDir = new File(rootDir);  
        if (!baseDir.exists() || !baseDir.isDirectory()){  
            return;
        }
        
        String[] list = baseDir.list();  
        if(list == null){
        	return;
        }
        for (int i = 0; i < list.length; i++) {
            File file = new File(rootDir + "/" + list[i]);  
            if(!file.isDirectory()) {
                tempName =  file.getName();
                if(tempName.equals(fileName)){
                    fileList.add(file.getAbsolutePath());
                    return;
                }
            } else if(file.isDirectory()){
            	if(depth < maxDepth){
                    findFiles(rootDir + "/" + list[i],fileName,fileList,depth,maxDepth);
            	}
            }
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: