java中Properties类及读取properties中属性值

本文为博主原创,未经允许不得转载:

      在项目的应用中,经常将一些配置放入properties文件中,在代码应用中读取properties文件,就需要专门的类Properties类,通过这个类可以进行读取。

深入理解和学习的参考的详见:深入理解和学习Properties参考  

    此处展现在项目中读取properties配置文件中的帮助类,代码可以直接使用:

*******注:读取properties文件中的属性也可以用spring  boot中的注解来读取,可参考我的标签中spring boot中如何快速获取properties中的配置属性值  

import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil
{

    public static final String FILE_PATH = "properties/upload.properties";

    //通过传入的路径及key,获得对应的值
    public static String getValue(String path, String key)
    {
        Properties properties = new Properties();
        try
        {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
        }
        catch (IOException e)
        {
            throw new RuntimeException("File Read Failed...", e);
        }
        return properties.getProperty(key);
    }
    //通过key直接获取对应的值
    public static String getValue(String key)
    {
        Properties properties = new Properties();
        try
        {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_PATH));
        }
        catch (IOException e)
        {
            throw new RuntimeException("File Read Failed...", e);
        }
        return properties.getProperty(key);
    }

}

 另外还需要在spring配置文件中,对属性文件在项目启动的时候进行初始化加载和解析:代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="configHelper" class="com.allcam.system.utils.ConfigHelper"
        init-method="init"> <!--进行初始化加载-->
    </bean>

    
</beans>
原文地址:https://www.cnblogs.com/zjdxr-up/p/7763485.html