Java中加载properties配置文件的几种方式


项目中有时候需要从配置文件中加载各种配置属性。

1.利用FileInputStream

这种方式比较适合从任意路径加载配置文件,文件路径是绝对路径。直接看代码

 //初始化资源加载器,boolean值指示加载成功还是失败
    private static boolean initialize(){

        try{
            try{
                stream = new FileInputStream("E:/info.properties");
                info = new Properties();
                info.load(stream);
            }finally {
                if(stream != null)
                    stream.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //获取配置信息
    public static String getProperties(String key){
        return info.getProperty(key);
    }

    public static void main(String[] args) {

        if(!initialize())return;
        System.out.println(getProperties("key"));
    }

2.利用ClassLoader对象的getResourceAsStream()

底层使用了类加载器加载,这种方式只能从classpath下加载配置文件,即src目录下的文件,路径是相对路径,从src开始写起

 //初始化资源加载器,boolean值指示加载成功还是失败
    private static boolean initialize(){

        try{
            try{
                stream = ResourceUtil.class.getClassLoader()
                        .getResourceAsStream("resources/info.properties");
                info = new Properties();
                info.load(stream);
            }finally {
                if(stream != null)
                    stream.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //获取配置信息
    public static String getProperties(String key){
        return info.getProperty(key);
    }

文件的存放路径如下:

用这种方式去加载绝对路径下的文件会出现错误,应避免使用。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM