Java 常用工具类(26) : maven项目读取resources下.properties文件

本文介绍了在Spring框架中如何使用两种不同的方法读取properties文件,包括利用PropertiesLoaderUtils和ClassPathResource,提供了详细的代码实现。

参考 : https://www.oschina.net/question/2272552_2269641?sort=time 


import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Properties;

/**
 * @Auther: liyue
 * @Date: 2019/4/29 10:25
 * @Description: 读取properties工具类
 */
public class PropertiesUtil {

    public static Properties getProperties(String path) {
        try {
            //获取配置文件,转换成流
            Properties properties = PropertiesLoaderUtils.loadAllProperties(path);
            return properties;
        } catch (Exception e) {
            return null;
        }
    }
}

或者


import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * @Auther: liyue
 * @Date: 2019/4/29 10:25
 * @Description: 读取properties工具类
 */
public class PropertiesUtil {

    public static Properties getProperties(String path) {
        try {
            //获取配置文件,转换成流
            String propertiesPath = path;
            InputStream in = null;
            try {
                // 开发环境读取
                URL url = PropertiesUtil.class.getClassLoader().getResource(propertiesPath);
                File file = new File(url.getFile());
                in = new FileInputStream(file);
            } catch (Exception e) {

            }
            if (in == null) {
                // 打车jar包部署后读取
                ClassPathResource classPathResource = new ClassPathResource(propertiesPath);
                in = classPathResource.getInputStream();
            }
            //创建properties对象
            Properties properties = new Properties();
            //加载流
            properties.load(in);
            return properties;
        } catch (Exception e) {
            return null;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值