怎样使jar包里的类能读取同在此jar包中的一个配置文件

来源:互联网 发布:中国检察网络培训学校 编辑:程序博客网 时间:2024/04/29 05:30

 问题:获取路径问题

单独项目:

//  Properties prop = loadProperties("config/" + fileName);



单独项目property-core:

//Properties prop = loadProperties("src/main/resources/config/" + fileName);这样获取没问题




如果把property-core 作为jar包引入到property-wechat-service里面时:会报错,找不到该系统文件。



 最后是这种形式:  Properties prop = loadProperties(path0+"config/" + config.properties);

path0即是classes路径。


观察编译后的文件可以知道文件都在classes下面。

故而应该转变思路,先获取该类编译后的路径,然后获取classes路径,最后根据配置文件路径来获取该配置文件的路径。




思路:所有的文件编译后都会放在classes目录下,我们获取这个目录就好了。

public class ConfigHelper {

                   String path= this.getClass().getResource("").getPath();//获取当前编译类的路径
System.out.println("--------------++++++++++1-------------"+path);
String path2= this.getClass().getResource("/").getPath();
System.out.println("--------------++++++++++2-------------"+path2);

                  int n=path.indexOf("com");
String path0=path.substring(0, n);//根据当前编译类的路径获取classes路径

System.out.println("--------------++++++++++0-------------"+path0);

           Properties prop = loadProperties(path0+"config/" + config.properties);

}

控制台打印:

--------------++++++++++1-------------/F:/information20170320/source/property-parent/property-core/target/classes/com/tianjian/property/jieshun/utils/
--------------++++++++++2-------------/F:/information20170320/source/property-parent/property-wechat-service/target/classes/

--------------++++++++++0-------------/F:/information20170320/source/property-parent/property-core/target/classes/

原创粉丝点击