Java读取properties配置文件三种方式

本文介绍了三种在Java中读取properties配置文件的方法:使用InputStream、ResourceBundle类和Spring的PropertiesLoaderUtils工具类。每种方法都有其适用场景,文章详细展示了如何实现。

原文链接:java读取properties配置文件的几种方式

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

1.基于InputStream读取配置文件

根据实际情况处理转码问题

    // 通过InputStream读取配置文件
    private static void readPropertiesByInputStream() {
        Properties properties = new Properties();
        InputStream inputStream = Object.class.getResourceAsStream("/code.properties");
        // Properties是用UTF-8编码的,所以需要用UTF-8解码
        // 很多人没有设置文本的编码,通常是GBK的,相应改成GBK即可
        InputStreamReader inputStreamReader = null;

        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            properties.load(inputStreamReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(properties.get("warshipType.1"));
    }
2. java.util.ResourceBundle类读取
    private static void readPropertyByResourceBundle(){
        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"),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }


3. Spring中的PropertiesLoaderUtils工具类进行获取
    private static void readPropertyBySpringUtils() {
        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();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值