JAVA获取属性文件(*.properties)内容

1.原因

为了更方便的获取.properties文件中的内容

2.方法

通过反射加载文件路径,获取文件流,然后读取流信息,获取指定数据 

Properties properties; 

1.

/**
 * 获取当前类文件编译之后存储路径
 * /D:/workSpace/mineSvnWorkSpace/demo/demo_core/demo_back/target/classes/com/cll/yl/demo/back/common/util/
 */
String currentPath = this.getClass().getResource("").getPath();
/**
 * 通过类加载器,获取项目编译过后根目录
 * /D:/workSpace/mineSvnWorkSpace/demo/demo_core/demo_back/target/classes/
 */
String rootPath = this.getClass().getClassLoader().getResource("").getPath();
if (StringUtils.isNotEmpty(rootPath)) {
    String filePath = rootPath + fileName;
    FileInputStream fileInputStream = new FileInputStream(filePath);
    InputStream inputStream = new BufferedInputStream(fileInputStream);
    // 解决获取配置文件中中文乱码问题
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
    Properties properties = new Properties();
    properties.load(inputStreamReader);
    properties.getProperty(keyName);
}

2.

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
if (null != inputStream) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
    properties = new Properties();
    properties.load(inputStreamReader);
    properties.getProperty(keyName);
}

3.如果使用了Spring框架,可以将*.properties的属性文件加载到Spring容器中,然后使用注解读取配置文件中的内容

<!--  引入参数配置文件         -->
<bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:system.properties</value>
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

system.properties文件中只有一行数据

dialect=MySQL

在需要使用的地方,进行如下操作

@Value("${dialect}")

private String dialect;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值