问题1:Java在Linux环境使用Properties读取配置文件properties.load()方法空指针异常。

情景: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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Nginx优化详解-------超详细 一、一般来说nginx 配置文件中对优化比较有作用的为以下几项: 1. w...
    name_cc2f阅读 3,757评论 0 1
  • 磁盘冗余RAID RAID就是廉价冗余磁盘阵列。简称为磁盘阵列 1、RAID的级别 Raid0、Raid1、Rai...
    puurutsjdy阅读 2,713评论 0 1
  • 一、请选择下面结果为true的表达式 null instanceof Object null == undefin...
    太夫使秦端雨阅读 3,961评论 0 1
  • 第1章 磁盘冗余阵列Raid技术知识与实践 1.1 什么是Raid Raid是廉价冗余磁盘阵列(Redundant...
    淺唱吶鍛慯阅读 3,624评论 0 0
  • 曾经看到过一种说法,女性对情绪的忍受力和控制力其实是更强的,所以她们会感受到,表达出来,表达出来意味有可能通过沟通...
    某天雨天阅读 3,607评论 0 1

友情链接更多精彩内容