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

**

Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易。

**

1.ClassLoder读取配置文件

     Properties properties = new Properties();
    // 使用ClassLoader加载properties配置文件生成对应的输入流
     InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("src/resouce/config.properties");
 // 使用properties对象加载输入流
     properties.load(in);
   //获取key对应的value值
     properties.getProperty(String key);

2. InputStream 读取配置文件

  Properties properties = new Properties();
 // 使用InPutStream流读取properties文件
 BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
 properties.load(bufferedReader);
 // 获取key对应的value值
 properties.getProperty(String key);

3 .通过 java.util.ResourceBundle 类来读取,这种方式比使用 Properties 要方便一些
  通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名

 properties.getProperty(String key);
//config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可  
 ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config"); String key = resource.getString("keyWord"); 

例子:

package com.test.properties;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

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

/**
 *
 * @ClassName: TestProperties
 * @Description: 获取配置文件信息
 * @date: 2017年11月25日 上午10:56:00
 * @version: 1.0.0
 */
public class TestProperties {


    /**
     *
     * @Title: printAllProperty
     * @Description: 输出所有配置信息
     * @param props
     * @return void
     * @throws
     */
    private static void printAllProperty(Properties props)
    {
        @SuppressWarnings("rawtypes")
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements())
        {
            String key = (String) en.nextElement();
            String value = props.getProperty(key);
            System.out.println(key + " : " + value);
        }
    }

    /**
     * 根据key读取value
     *
     * @Title: getProperties_1
     * @Description: 第一种方式:根据文件名使用spring中的工具类进行解析
     *                  filePath是相对路劲,文件需在classpath目录下
     *                   比如:config.properties在包com.test.config下,
     *                路径就是com/test/config/config.properties
     *
     * @param filePath
     * @param keyWord
     * @return
     * @return String
     * @throws
     */
    public static String getProperties_1(String filePath, String keyWord){
        Properties prop = null;
        String value = null;
        try {
            // 通过Spring中的PropertiesLoaderUtils工具类进行获取
            prop = PropertiesLoaderUtils.loadAllProperties(filePath);
            // 根据关键字查询相应的值
            value = prop.getProperty(keyWord);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 读取配置文件所有信息
     *
     * @Title: getProperties_1
     * @Description: 第一种方式:根据文件名使用Spring中的工具类进行解析
     *                  filePath是相对路劲,文件需在classpath目录下
     *                   比如:config.properties在包com.test.config下,
     *                路径就是com/test/config/config.properties
     *
     * @param filePath
     * @return void
     * @throws
     */
    public static void getProperties_1(String filePath){
        Properties prop = null;
        try {
            // 通过Spring中的PropertiesLoaderUtils工具类进行获取
            prop = PropertiesLoaderUtils.loadAllProperties(filePath);
            printAllProperty(prop);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key读取value
     *
     * @Title: getProperties_2
     * @Description: 第二种方式:使用缓冲输入流读取配置文件,然后将其加载,再按需操作
     *                    绝对路径或相对路径, 如果是相对路径,则从当前项目下的目录开始计算,
     *                  如:当前项目路径/config/config.properties,
     *                  相对路径就是config/config.properties
     *
     * @param filePath
     * @param keyWord
     * @return
     * @return String
     * @throws
     */
    public static String getProperties_2(String filePath, String keyWord){
        Properties prop = new Properties();
        String value = null;
        try {
            // 通过输入缓冲流进行读取配置文件
            InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
            // 加载输入流
            prop.load(InputStream);
            // 根据关键字获取value值
            value = prop.getProperty(keyWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 读取配置文件所有信息
     *
     * @Title: getProperties_2
     * @Description: 第二种方式:使用缓冲输入流读取配置文件,然后将其加载,再按需操作
     *                    绝对路径或相对路径, 如果是相对路径,则从当前项目下的目录开始计算,
     *                  如:当前项目路径/config/config.properties,
     *                  相对路径就是config/config.properties
     *
     * @param filePath
     * @return void
     * @throws
     */
    public static void getProperties_2(String filePath){
        Properties prop = new Properties();
        try {
            // 通过输入缓冲流进行读取配置文件
            InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
            // 加载输入流
            prop.load(InputStream);
            printAllProperty(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key读取value
     *
     * @Title: getProperties_3
     * @Description: 第三种方式:
     *                    相对路径, properties文件需在classpath目录下,
     *                  比如:config.properties在包com.test.config下,
     *                  路径就是/com/test/config/config.properties
     * @param filePath
     * @param keyWord
     * @return
     * @return String
     * @throws
     */
    public static String getProperties_3(String filePath, String keyWord){
        Properties prop = new Properties();
        String value = null;
        try {
            InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
            prop.load(inputStream);
            value = prop.getProperty(keyWord);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 读取配置文件所有信息
     *
     * @Title: getProperties_3
     * @Description: 第三种方式:
     *                    相对路径, properties文件需在classpath目录下,
     *                  比如:config.properties在包com.test.config下,
     *                  路径就是/com/test/config/config.properties
     * @param filePath
     * @return
     * @throws
     */
    public static void getProperties_3(String filePath){
        Properties prop = new Properties();
        try {
            InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
            prop.load(inputStream);
            printAllProperty(prop);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        // 注意路径问题
        String properties_1 = getProperties_1("com/test/config/config.properties", "wechat_appid");
        System.out.println("wechat_appid = " + properties_1);
        getProperties_1("com/test/config/config.properties");
        System.out.println("*********************************************");
        // 注意路径问题
        String properties_2 = getProperties_2("configure/configure.properties", "jdbc.url");
        System.out.println("jdbc.url = " + properties_2);
        getProperties_2("configure/configure.properties");
        System.out.println("*********************************************");
        // 注意路径问题
        String properties_3 = getProperties_3("/com/test/config/config.properties", "wechat_appid");
        System.out.println("wechat_appid = " + properties_3);
        getProperties_3("/com/test/config/config.properties");
    }
}

转载地址:https://www.cnblogs.com/sebastian-tyd/p/7895182.html

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot读取application.properties的值的方式有多种方法。一种常用的方式是通过使用@Value注解来注入属性值。可以在需要使用属性值的字段、方法的参数、方法的返回值上添加@Value注解,并指定要注入的属性的键名。例如,可以使用@Value("${spring.rabbitmq.host}")来注入application.properties文件中的spring.rabbitmq.host属性的值。这样,在程序运行时,Spring Boot会自动读取属性文件中的值,并将其注入到相应的位置。 另一种方式是使用PropertiesLoaderUtils类来读取属性文件的值。首先,需要导入java.util.Properties和org.springframework.core.io.support.PropertiesLoaderUtils类。然后,可以使用PropertiesLoaderUtils的loadProperties方法来加载属性文件,然后使用getProperty方法获取具体的属性值。例如,可以使用Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"))来加载application.properties文件,然后使用properties.getProperty("spring.rabbitmq.host")来获取spring.rabbitmq.host属性的值。 总结起来,Spring Boot提供了多种方式读取application.properties文件的值,可以根据具体的需求选择适合的方式来获取属性值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring Boot中配置文件application.properties使用](https://download.csdn.net/download/weixin_38672800/12765190)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringBoot获得application.properties中数据的几种方式](https://blog.csdn.net/m0_67393686/article/details/124421983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringBoot读取application.properties配置文件](https://blog.csdn.net/watson2017/article/details/124732267)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗小稳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值