All Downloads are FREE. Search and download functionalities are using the official Maven repository.

framework.utils.ClassResourceUtil Maven / Gradle / Ivy

There is a newer version: 1.8.2
Show newest version
package framework.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 类资源加载
 */
public class ClassResourceUtil {

    /**
     * 检索资源
     *
     * @param pattern
     * @return
     * @throws IOException
     */
    public static List searchResources(String pattern) throws IOException {
        return searchResources(pattern, null);
    }

    /**
     * 检索资源
     *
     * @param pattern
     * @param dirname 需要去除的目录名称
     * @return
     * @throws IOException
     */
    public static List searchResources(String pattern, String dirname) throws IOException {
        List list = new ArrayList<>();

        //
        String p0 = null;
        if (StringUtils.isNotBlank(dirname)) {
            URL dirPath = ClassLoader.getSystemResource(dirname);
            if (dirPath == null) {
                throw new IOException("Not found dir name " + dirname);
            }
            p0 = dirPath.getPath();
        }

        //
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:" + pattern);

        //
        if (p0 == null) {
            for (Resource resource : resources) {
                list.add(resource.getURL().getPath());
            }
        } else {
            for (Resource resource : resources) {
                String p1 = resource.getURL().getPath();
                if (p1.startsWith(p0)) {
                    list.add(p1.substring(p0.length()));
                }
            }
        }

        //
        return list;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy