如何知道某个class所在的jar包+如何读取指定jar包内的文件

为什么会出现这个问题?

因为实际项目太多,包太多,管理如果没有做好严格区分好,有时候就得用技术屏蔽一下了。

 

如何知道某个class所在的jar包

    public static void scanNativeClassJar(Class<?> clazz){
        System.out.println("clazz.getSimpleName():" + clazz.getSimpleName());
        System.out.println("clazz.getCanonicalName():" + clazz.getCanonicalName());//这个名字不行哦
        System.out.println(clazz.getResource(clazz.getSimpleName() + ".class"));
    }

输出:

clazz.getSimpleName():TestBbb

clazz.getCanonicalName():com.xxx.prac.jarloadfile.testa.TestBbb

jar:file:/D:/workjava/jar-file-load-test/test-main/lib/test-b.jar!/com/xxx/prac/jarloadfile/testa/TestBbb.class

 

如何读取指定jar包内的文件

参考:http://mushiqianmeng.blog.51cto.com/3970029/833649/

/** 
 * 从ClassPath中的Jar包读取某文件夹下的所有文件 
 *  
 * @author lihzh 
 * @throws IOException  
 * @data 2012-4-13 下午10:22:24 
 */ 
@Test 
public void testGetFilesFromJarInClassPathWithDirPath() throws IOException { 
    String dirPath = "conf/"; 
    URL url = this.getClass().getClassLoader().getResource(dirPath); 
    Assert.assertNotNull(url); 
    String urlStr = url.toString(); 
    // 找到!/ 截断之前的字符串 
    String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2); 
    URL jarURL = new URL(jarPath); 
    JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection(); 
    JarFile jarFile = jarCon.getJarFile(); 
    Enumeration<JarEntry> jarEntrys = jarFile.entries(); 
    Assert.assertTrue(jarEntrys.hasMoreElements()); 
    Properties props = new Properties(); 
    while (jarEntrys.hasMoreElements()) { 
        JarEntry entry = jarEntrys.nextElement(); 
        // 简单的判断路径,如果想做到想Spring,Ant-Style格式的路径匹配需要用到正则。 
        String name = entry.getName(); 
        if (name.startsWith(dirPath) && !entry.isDirectory()) { 
            // 开始读取文件内容 
            InputStream is = this.getClass().getClassLoader().getResourceAsStream(name); 
            Assert.assertNotNull(is); 
            props.load(is); 
        } 
    } 
    Assert.assertTrue(props.containsKey("test.key")); 
    Assert.assertEquals("thisIsValue", props.getProperty("test.key")); 
    Assert.assertTrue(props.containsKey("test.key.two")); 
    Assert.assertEquals("thisIsAnotherValue", props.getProperty("test.key.two")); 
} 

 

 

来自baidu的一个回答,本质是一样的。

项目迁移的过程中发现以前的代码维护性实在是差。
我把问题简化为以下这些简单的代码:

项目M 引用了项目 A.jar,这个A在lib目录里面
在A里面放置了一个配置文件test.properties, 就放在jar的根目录下。
A.jar  
|___test.properties

在M中有一段代码回去读取这个A.jar里的配置文件,简单一点就用下面这句话来调用。

Java code

public class ConfigUtil {
    public static String getInstance() throws Exception{
        
        String path = ConfigUtil.class.getResource("/").toString();
        path  = path.substring(0, path.length()-8);//
        System.out.println(path);//这里打印的结果显示可以拿到当前类的绝对路径
        InputStream f = new FileInputStream("jar:"+path+"lib!/A.jar/"+"test.properties");
        return "xxx";
    }
}

 

 

 

+

+

=

+++

=

+

+

猜你喜欢

转载自fantaxy025025.iteye.com/blog/2288086