没打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 =(InputStream) AppMain.class.getResourceAsStream("/config.properties");
BufferedReader ipss=new BufferedReader(new InputStreamReader(ips));
pro.load(ipss);
BasicType.rootURL = pro.getProperty("scrURL");
BasicType.stationPath = pro.getProperty("stationPath");
BasicType.resultPath = pro.getProperty("resultPath");
BasicType.startTime = pro.getProperty("startTime");
BasicType.endTime = pro.getProperty("endTime");
return value;
} catch (FileNotFoundException e) {
System.out.println("无法找到文件:"+filePath);
return null;
} catch (IOException e) {
System.out.println("读文件出错:"+filePath+"---"+e.getMessage());
return null;
}
}
备注:在使用过程中一定要使用 java.io.InputStream引用,而不是使用:org.omg.CORBA.portable.InputStream引用。