递归获取某个路径下的所有文件

package spring.agent;

import java.io.File;

import org.junit.Test;

public class FileNameTest {

    private final String host = "http://localhost:7081/wcl-web/";
    private final String rootPath = "D:/MyWorkSpacePractice/ACL/wcl-web/src/main/webapp/WEB-INF/pages";

    @Test
    public void getFileName() {
        File file = new File(rootPath);
        getFileName(file);
    }

    public void getFileName(File file) {

        File[] listFiles = file.listFiles();
        if (file.isDirectory() && listFiles.length > 0) {
            for (int i = 0; i < listFiles.length; i++) {
                getFileName(listFiles[i]);
            }
        } else {
            System.out.println(getFileParentPath(file));
            makeUrl(getFileParentPath(file));
        }
    }

    public void makeUrl(String absolutePath) {
        String httpUrl = absolutePath.replace("\\", "/").replace(rootPath + "/", host + "test/")
                .replace("/final/", "/1/").replace("/includes/", "/0/").replace(".ftl", "");
        if (!(httpUrl.contains("/test/1") || httpUrl.contains("/test/0"))) {
            httpUrl = httpUrl.replace("/test/", "/test/3/");
        }
        System.out.println(httpUrl);
        // absolutePath.startsWith("")
    }

    public String getFileParentPath(File file) {
        File filePath = new File(file.getAbsolutePath());

        String path = filePath.getAbsolutePath();

        while (path.equals(rootPath)) {
            File fileLoop = filePath.getParentFile();
            path = fileLoop.getAbsolutePath();
        }
        return path;
    }

}

  其中在file.listfile时候,可以加一些过滤条件

// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
    // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
    public boolean accept(File file) {
        return (recursive && file.isDirectory())
                || (file.getName().endsWith(".class"));
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值