两个不同jar包下相同的配置文件获取

两个不同jar包下相同文件的获取:

1、创建3个工程(test,test2 ,testDemo)

   test和test2 资源目录下有相同的配置文件(/META/prop.properties)

  testDemo 为获取配置文件的工程;

两个不同jar包下相同的配置文件获取

testDemo代码:

import java.io.*;
import java.net.URL;
import java.util.Enumeration;

public class DemoApplication {

    public static void main(String... arg) {
        readProp();
        System.out.println("-------------");
        scanProps();
    }

    public static void readProp() {
        InputStream is = DemoApplication.class.getResourceAsStream("/META-INF/prop.properties");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s = "";
        try {
            while ((s = br.readLine()) != null){
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void scanProps(){
        Enumeration<URL> urls = null;
        URL url = null;
        try {
            urls = Thread.currentThread().getContextClassLoader().getResources("META-INF/prop.properties");
            System.out.println("是否发现有文件?" + urls.hasMoreElements());
        } catch (IOException e) {
            e.printStackTrace();
        }

        while(urls.hasMoreElements()) {
            InputStream in = null;
            try {
                in = urls.nextElement().openStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String s = "";
                while ((s = br.readLine()) != null){
                    System.out.println(s);
                }
            } catch (Exception e){
                e.printStackTrace();
            }finally {
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

输出:

name=test
-------------
是否发现有文件?true
name=test
name=test2

注:我们能通过

InputStream is = DemoApplication.class.getResourceAsStream("/META-INF/prop.properties"); 

只能获取的第一个jar包的配置文件,

通过

 urls = Thread.currentThread().getContextClassLoader().getResources("META-INF/prop.properties");

我们能获取到所有jar包下的文件

通过getResourceAsStream获取需要需要在路径中添加根路径符号'/'

而通过classLoader.getResource 获取则不能添加根路径符号'/'