读取资源工具

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * File Name : ResourceUtil.java
 *
 * @Description : 资源信息工具类
 */
public class ResourceUtil
{
    private static Logger logger = Logger.getLogger(ResourceUtil.class
            .getName());

    /**
     * Description : 包分隔符 Author : 904370
     */
    public static char PACK_SEP = '.';

    public static char PACK_FILE_SEP = '/';

    private static char FILE_SEP_CHAR = File.separatorChar;

    public static String DIR_TYPE = "directory";

    public static String COSHIP_PACK = "com.coship";

    public static Set<String> COSHIP_BUSINESS_PACK = getResources(COSHIP_PACK,
            DIR_TYPE, false);

    /**
     * Description : 获得包路径下某类型的所有资源
     *
     * @param pack
     *            包路径
     * @param type
     *            文件类型
     * @param recursive
     *            是否递归下级
     * @return
     *
     */
    public static Set<String> getResources(String pack, String type,
            boolean recursive)
    {
        // 资源路径集合
        Set<String> resources = new HashSet<String>();

        // 获取包的名字 并进行替换
        String packageName = pack;
        String packageDirName = packageName.replace(PACK_SEP, PACK_FILE_SEP);
        // 定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try
        {
            dirs = Thread.currentThread().getContextClassLoader().getResources(
                    packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements())
            {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol))
                {
                    logger.info("file类型的扫描");
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    Set<String> filePathResources = new HashSet<String>();
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddResourcesInPackageByFile(packageName, filePath,
                            type, recursive, filePathResources);
                    filePath = deleteHead(filePath, PACK_FILE_SEP);
                    // 去除路径中包路径
                    filePath = filePath.substring(0, filePath.length()
                            - (packageDirName.length() + 1));
                    for (String filePathResource : filePathResources)
                    {
                        filePathResource = StringUtils.replace(
                                filePathResource, "" + FILE_SEP_CHAR, ""
                                        + PACK_FILE_SEP);
                        filePathResource = filePathResource.substring(filePath
                                .length(), filePathResource.length());
                        resources.add(filePathResource);
                    }
                } else if ("jar".equals(protocol))
                {
                    // 如果是jar包文件
                    // 定义一个JarFile
                    logger.info("jar类型的扫描");
                    JarFile jar;
                    try
                    {
                        // 获取jar
                        jar = ((JarURLConnection) url.openConnection())
                                .getJarFile();
                        // 从此jar包 得到一个枚举类
                        Enumeration<JarEntry> entries = jar.entries();
                        // 同样的进行循环迭代
                        String tempPackageDirName = packageDirName;
                        while (entries.hasMoreElements())
                        {
                            // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            name = deleteHead(name, PACK_FILE_SEP);
                            // 如果前半部分和定义的包名相同
                            if (name.startsWith(packageDirName)
                                    || name.startsWith(tempPackageDirName))
                            {
                                int idx = name.lastIndexOf(PACK_FILE_SEP);
                                // 如果以"/"结尾 是一个包
                                if (idx != -1)
                                {
                                    if (DIR_TYPE.equals(type)
                                            || StringUtils.isBlank(type))
                                    {
                                        if (recursive)
                                        {
                                            name = deleteLast(name,
                                                    PACK_FILE_SEP);
                                            resources.add(name);
                                        } else
                                        {
                                            // 只给下一级增加
                                            int pos = name
                                                    .indexOf(
                                                            PACK_FILE_SEP,
                                                            packageDirName
                                                                    .length() + 1);
                                            if (pos == name.length() - 1)
                                            {
                                                name = deleteLast(name,
                                                        PACK_FILE_SEP);
                                                resources.add(name);
                                            }

                                        }

                                    }
                                    // 如果可以递归下级就改变包路径为下级路径
                                    if (recursive)
                                    {
                                        tempPackageDirName = name.substring(0,
                                                idx);
                                    }

                                }
                                // 如果可以迭代下去 并且是一个包
                                if (!entry.isDirectory())
                                {
                                    // 不是目录
                                    if (StringUtils.isNotBlank(type))
                                    {
                                        if (name.endsWith("." + type))
                                        {
                                            resources.add(name);
                                        }
                                    } else
                                    {
                                        resources.add(name);
                                    }

                                }
                            }
                        }
                    } catch (IOException e)
                    {
                        logger.error("在扫描用户定义视图时从jar包获取文件出错!", e);
                    }
                }
            }
        } catch (IOException e)
        {
            logger.error("在扫描用户定义视图时获取路径出错!", e);
        }
        return resources;
    }

    public static void findAndAddResourcesInPackageByFile(String packageName,
            String packagePath, String type, final boolean recursive,
            Set<String> resources)
    {
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory())
        {
            logger.warn("用户定义包名 " + packageName + " 下没有任何文件");
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles();
        // 循环所有文件
        for (File file : dirfiles)
        {
            // 如果是目录 则继续扫描
            if (file.isDirectory())
            {
                if (DIR_TYPE.equals(type) || StringUtils.isBlank(type))
                {
                    resources.add(file.getAbsolutePath());
                }
                findAndAddResourcesInPackageByFileRecursive(packageName
                        + PACK_SEP + file.getName(), file.getAbsolutePath(),
                        type, recursive, resources);
            } else
            {
                if (StringUtils.isNotBlank(type))
                {
                    if (!DIR_TYPE.equals(type)
                            && file.getName().endsWith("." + type))
                    {
                        resources.add(file.getAbsolutePath());
                    }
                }
            }
        }
    }

    public static void findAndAddResourcesInPackageByFileRecursive(
            String packageName, String packagePath, String type,
            final boolean recursive, Set<String> resources)
    {
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory())
        {
            logger.warn("用户定义包名 " + packageName + " 下没有任何文件");
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles(new FileFilter()
        {
            // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
            public boolean accept(File file)
            {
                return (recursive && file.isDirectory());
            }
        });
        // 循环所有文件
        for (File file : dirfiles)
        {
            // 如果是目录 则继续扫描
            if (file.isDirectory())
            {
                if (DIR_TYPE.equals(type) || StringUtils.isBlank(type))
                {
                    resources.add(file.getAbsolutePath());
                }
                findAndAddResourcesInPackageByFileRecursive(packageName
                        + PACK_SEP + file.getName(), file.getAbsolutePath(),
                        type, recursive, resources);
            } else
            {
                if (StringUtils.isNotBlank(type))
                {
                    if (!DIR_TYPE.equals(type)
                            && file.getName().endsWith("." + type))
                    {
                        resources.add(file.getAbsolutePath());
                    }
                }
            }
        }
    }

    private static String deleteHead(String filePath, char lastChar)
    {
        if (filePath.charAt(0) == lastChar)
        {
            // 获取后面的字符串
            filePath = filePath.substring(1);
        }
        return filePath;
    }

    private static String deleteLast(String name, char lastChar)
    {
        if (name.charAt(name.length() - 1) == lastChar)
        {
            // 获取后面的字符串
            name = name.substring(0, name.length() - 1);
        }
        return name;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值