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; } }