EXE4J打成jar包后无法读取到jar包内的properties文件
发现在eclipse里一切正常,但打成jar包后就无法读取到properties文件了。
之前的程序是这样获取配置文件的:
Thread.currentThread().getContextClassLoader().getResource("").getPath() +filename+".properties")
来获取properties文件,但发现一运行就报错.后来将代码改成:
this.getClass().getClassLoader().getResourceAsStream(filename+".properties")
一般在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,
相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要重新打jar包,那是相当的麻烦。。
既然这么麻烦,你肯定想将配置文件放在其他的目录下,生成的jar包内不包含相应的配置文件,
修改配置文件无需重新打包,没错,下面就是一种解决方案了。
读取jar包内配置文件:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");
读取jar包外配置文件:
String filePath = System.getProperty("user.dir") + "/conf/configfilename.properties";
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
2、private static void load(){
try {
/**
* 加载资源文件地第一种方式
*
* **/
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config/config.properties") ;
/**
* 加载资源文件的第二种方式
*
* 如果使用这种方式,生成jar包运行时,会提示找不到config.properties
* **/
// FileInputStream fis = new FileInputStream(
// PropertiesUtil.class.getClassLoader().getResource("config/config.properties") .getPath()
// );
// System.out.println("1");
// ClassLoader cl = PropertiesUtil.class.getClassLoader() ;
// System.out.println("2");
// URL url = cl.getResource("com/check/util/config.properties") ;
// System.out.println(url);
// String path = url.getPath() ;
// File file = new File("config/config.properties") ;
props = new Properties() ;
props.load(in);
} catch (Exception e) {
e.printStackTrace() ;
}
}
/**
* @function:获取资源文件中的值
* @Author:2012-5-19 下午06:36:31
* @param: @param key 资源文件中的key
* @param: @return key对应的值
* @return String
*/
public String getValue(String key){
return props.getProperty(key) ;
}
public static void main(String[] args) {
System.out.println(PropertiesUtil.getInstance().getValue("service.id"));
}
注意:
如果使用这种方式加载加载资源文件
FileInputStream fis = new FileInputStream(
// PropertiesUtil.class.getClassLoader().getResource("config/config.properties") .getPath()
// );
生成的jar文件运行的时候,会报找不到properties文件,这时会使用这种方式加载资源文件。
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config/config.properties") ;