Loading

获取类路径中含有beans.xml的jar包名称

获取类路径中含有beans.xml的jar包名称

package com.stono;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarFile;

public class LoadJars {
    public static void main(String[] args) throws IOException {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        System.out.println(contextClassLoader);
        Enumeration<URL> resources = contextClassLoader.getResources("META-INF/beans.xml"); // MANIFEST.MF
        Set<String> jarNames = new LinkedHashSet<>();
        String separator = File.separator;
        System.out.println(separator);
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            System.out.println(url);
            String protocol = url.getProtocol();
            System.out.println(protocol); // 竟然是jar
            if ("jar".equals(protocol)) {
                JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
                String name = jarFile.getName();
                System.out.println(name);
                if (name.indexOf(separator) == -1) {
                    jarNames.add(name);
                    continue;
                }
                String jarName = name.substring(name.lastIndexOf(separator) + separator.length(), name.length());
                jarNames.add(jarName);
            }
        }
        System.out.println(jarNames);
        // toArray还可以输入参数;
        System.out.println(jarNames.toArray(new String[]{}));
        System.out.println(jarNames.toArray()); // 这个就是object数组了;

    }
}

 

posted @ 2018-05-16 09:30  stono  阅读(200)  评论(0编辑  收藏  举报