java读取properties配置文件的几种方式

项目中经常将一些配置信息放到properties文件中,读取非常方便,下面介绍几种java读取properties配置文件的方式。先看示例的properties文件:在这里插入图片描述
方法一,基于InputStream读取配置文件:

public static void main(String[] args) {
    readProperty1();
}

//方法一
private static void readProperty1() {
    Properties properties = new Properties();
    InputStream inputStream = Object.class.getResourceAsStream("/code.properties");
    try {
        properties.load(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(properties.get("warshipType.1"));
}

执行后,结果如下:

在这里插入图片描述
发现是乱码,分析后发现properties文件默认的用的GBK编码的,所以需要用GBK解码,代码修改如下:

发现properties.load(inputStreamReader);这句代码报红,分析发现是java编译版本的问题,如图:
在这里插入图片描述
原来需要1.6以上的版本,修改后,如图:
在这里插入图片描述
最后,执行程序,结果如图:
在这里插入图片描述
方法二,通过Spring中的PropertiesLoaderUtils工具类进行获取:

//方法二
private static void readProperty2() {
    Properties properties = new Properties();
    try {
        properties = PropertiesLoaderUtils.loadAllProperties("code.properties");
        System.out.println(new String(properties.getProperty("warshipType.2").getBytes("iso-8859-1"), "gbk"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

执行结果如图:在这里插入图片描述
顺便介绍一下遍历取值的方法:

//方法二
private static void readProperty2() {
    Properties properties = new Properties();
    try {
        properties = PropertiesLoaderUtils.loadAllProperties("code.properties");
        //遍历取值
        Set<Object> objects = properties.keySet();
        for (Object object : objects) {
            System.out.println(new String(properties.getProperty((String) object).getBytes("iso-8859-1"), "gbk"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

执行结果如图:在这里插入图片描述
方法三,通过 java.util.ResourceBundle 类读取:

//方法三
private static void readProperty3() {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("code");
    //遍历取值
    Enumeration enumeration = resourceBundle.getKeys();
    while (enumeration.hasMoreElements()) {
        try {
            String value = resourceBundle.getString((String) enumeration.nextElement());
            System.out.println(new String(value.getBytes("iso-8859-1"), "gbk"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

执行结果如图:在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值