情景:IDE中使用Properties读取配置文件正常,打成jar包后在Linux下执行,properties.load()方法空指针异常,但是文件输入流可以按照路径读取配置文件。
源代码
该部分代码可在IDE无问题,打成Jar包在Linux执行出现空指针异常。
String basepath = System.getProperty("user.dir");
InputStream ins=ClassLoader.getSystemResourceAsStream(basepath+File.separator+"db.properties");
props.load(ins);
driver=props.getProperty("driver");
url=props.getProperty("url");
url2=props.getProperty("url2");
user=props.getProperty("user");
password=props.getProperty("password");
rt_ip=props.getProperty("rt_ip");
rt_user=props.getProperty("rt_user");
rt_pwd=props.getProperty("rt_pwd");
backups_path=props.getProperty("backups_path");
修改源代码:
jdk自带的ResourceBundle 工具类,实现properties配置文件的加载。该方法可以将项目打Jar包后动态修改配置文件,而无需修改工程代码。
private static ResourceBundle bundle;
private static BufferedInputStream inputStream;
static{
try {
String basepath = System.getProperty("user.dir");
inputStream=new BufferedInputStream(new FileInputStream(basepath+File.separator+"exporter.config"));
bundle=new PropertyResourceBundle(inputStream);
driver=bundle.getString("driver");
url=bundle.getString("url");
url2=bundle.getString("url2");
user=bundle.getString("user");
password=bundle.getString("password");
rt_ip=bundle.getString("rt_ip");
rt_user=bundle.getString("rt_user");
rt_pwd=bundle.getString("rt_pwd");
backups_path=bundle.getString("backups_path");
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}