java遍历一个目录中不包括当前目录的其他所有父级目录

现在有一个功能,需要在一个目录中排除这个目录以外的所有其他目录,把要排除的目录列出来。例如:根目录为/a,不排除的目录是/a/b/c/d,c级目录级c级以上的所有目录和文件都要排除,其中要求不排除目录的所有父级目录都不排除,如本例中/a/b/c不排除,但是/a/b/e则要排除;排除文件有格式要求,例如,排除目录/a/b,则要求加上**/a/b/**,文件则不用加末尾斜杠及两个星号。按照向上遍历的思路,代码如下:

package com.thunisoft.svn;

import java.io.File;

public class Utils {
    /**
     * @param file 当前所在目录被排除的目录
     * @param rootFile 根目录
     * @return 当前目录不包括被排除的目录
     */
    public String get(File file,File rootFile){
        StringBuffer sb=new StringBuffer();
        File[] fileList=file.getParentFile().listFiles();
        for(File f:fileList){
            if(!f.getPath().equals(file.getPath())){
                sb.append("**"+f.getPath().replace(rootFile.getPath(), "").replace("\\\\", "/"));
                if(f.isDirectory()){//文件夹处理
                    sb.append("/**");
                }
                sb.append(";");
            }
        }
        String result=sb.toString();
        if(System.getProperties().getProperty("os.name").toLowerCase().startsWith("windows")){
            result.replace("//", "/");//处理Windows系统文件路径斜杠问题
        }
        return result;
    }
    /**
     * 
     * @param projectPath 项目目录
     * @param rootPath 根目录
     * @return
     */
    public String getAll(String projectPath,String rootPath){
        StringBuffer sb=new StringBuffer();
        File file=new File(projectPath);
        File rootFile=new File(rootPath);
        while(!file.getPath().equals(rootFile.getPath())){//遍历目录的父级目录,直到根目录
            sb.append(get(file, rootFile)+"\n");
            file=file.getParentFile();
        }
        String result=sb.toString();
        return result.substring(0, result.length()-2);//去掉末尾分号
    }

    public static void main(String[] args) {
        Utils u=new Utils();
        String rootPath="E:/a/rootPath";
        String projectPath="E:/a/rootPath/a/b/c";
        System.out.println(u.getAll(projectPath,rootPath));
    }

}

猜你喜欢

转载自yhan219.iteye.com/blog/2353673
今日推荐