您的位置:首页 > 编程语言 > Java开发

java读取jar包中的资源文件或properties配置文件路径的方法

2015-09-07 12:16 811 查看
没打jar包之前,是通过

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getFile();


获得当前路径然后再加上配置文件所在的目录获得绝对路径的方式,找到config.properties文件。

可是打了jar包以后马上就出错了,找不到文件!不管是用绝对路径还是相对路径都不行,只好百度之。

参考了这个http://wjl198408.blog.163.com/blog/static/25402147201211494859763/

原来是需要使用 getResourceAsStream 方法来直接获取InputStream对象,而不是通过文件路径获取。

获取完InputStream对象后别忘了再转换成BufferReader,否则后面load的时候还是会报错的。下面贴出完成代码:

public static String readValue(String filePath, String key) {
Properties props = new Properties();
try {
// InputStream ips = new BufferedInputStream(new FileInputStream(filePath));
InputStream ips = PropertiesUtils.class.getResourceAsStream("/config/app.properties");
BufferedReader ipss = new BufferedReader(new InputStreamReader(ips));
props.load(ipss);
String value = props.getProperty(key);
return value;
} catch (FileNotFoundException e) {
System.out.println("无法找到文件:"+filePath);
return null;
} catch (IOException e) {
System.out.println("读文件出错:"+filePath+"---"+e.getMessage());
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: