你会几种读取/加载 properties配置文件方法

x33g5p2x  于2022-02-07 转载在 其他  
字(7.1k)|赞(0)|评价(0)|浏览(251)

**摘要:**在java项目中经常会使用到配置文件,这里就介绍几种加载配置文件的方法。

本文分享自华为云社区《【Java】读取/加载 properties配置文件的几种方法》,作者:Copy工程师。

说明

在java项目中经常会使用到配置文件,这里就介绍几种加载配置文件的方法

目录结构

我是使用的maven搭建的项目,resources其实就是在根目录下
配置文件很简单

一、 基于ClassLoader读取配置文件

注意:有局限性只能在类路径下比较方便

Properties properties = new Properties();
// 注意这里的路径是根据根目录写的
InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties");
properties.load(in);
System.out.println("1111111111111---->:"+properties.getProperty("name"));

输出:
1111111111111---->:xing

二、基于InputStream读取配置文件

Properties properties2 = new Properties();
// 以下两种获取文件流的方式都可以,对于小文件第一种更快一点

// 通过BufferedReader获取文件流
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
    properties2.load(bufferedReader);
    System.out.println("22222222222---->:"+properties2.getProperty("name"));
}catch (Exception e){
    e.printStackTrace();
}
// 通过FileInputStreamm获取文件流
InputStream in2 = new FileInputStream(new File(filePath));
properties2.load(in2);
System.out.println("22222222222---->:"+properties2.getProperty("name"));

输出:
22222222222---->:xing
22222222222---->:xing

三、基于ResourceBundle读取配置文件

// 1. 通过ResourceBundle.getBundle() 静态方法来获取文件 这种方式不需要添加后缀名
 // 注意这里的ResourceBundle.getBundle("conf/demo") 这里不需要写配置文件的后缀 只需要名字即可 xml没试过 这里是properties
ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
System.out.println("333333333333----->:"+resourceBundle.getString("name"));
// 2. 通过InputStream读取文件
InputStream in3 = new FileInputStream(new File(filePath));
ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
System.out.println("333333333333----->:"+resourceBundle2.getString("name"));

输出:
333333333333----->:xing
333333333333----->:xing

四、基于PropertiesConfiguration读取配置文件 需要使用第三方的包

这是我推荐使用的方法,毕竟有大腿在,干嘛不去抱大腿,嘿嘿。我使用的包是commons-configuration2.x 。记住这是版本2 ,不是版本1, 2和1有很大的差别的。

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-configuration2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.2</version>
</dependency>

try {
	// 直接通过路径读取文件
    Configurations configurations = new Configurations();
    FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
    PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
    System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
    //通过reader 读取文件 找了找好像没有通过InputStream读取文件的方式
    PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
    propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
    System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
} catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
    e.printStackTrace();
}

输出:
444444444444----->:xing
555555555555----->:xing

整个类:

package com.xing.test;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import java.io.*;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class ReadProperties {
    public static void main(String[] args) throws IOException {
        String filePath = ReadProperties.class.getClassLoader().getResource("conf/demo.properties").getPath();

        /** 方法一
         *  基于ClassLoader读取配置文件
         *  有局限性 只能在类路径下比较方便
         */
        Properties properties = new Properties();
        // 注意这里的路径是根据target/classes 的路径写的
        InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties");
        properties.load(in);
        System.out.println("1111111111111---->:"+properties.getProperty("name"));
        /** 方法二
         *  基于InputStream读取配置文件
         *
         */
        Properties properties2 = new Properties();
        // 两种获取文件流的方式都可以,对于小文件第一种更快一点
        // 通过BufferedReader获取文件流
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
            properties2.load(bufferedReader);
            System.out.println("22222222222---->:"+properties2.getProperty("name"));
        }catch (Exception e){
            e.printStackTrace();
        }
        // 通过FileInputStreamm获取文件流
        InputStream in2 = new FileInputStream(new File(filePath));
        properties2.load(in2);
        System.out.println("22222222222---->:"+properties2.getProperty("name"));
        /** 方法三
         *  基于ResourceBundle读取配置文件
         *
         */
        // 1. 通过ResourceBundle.getBundle() 静态方法来获取文件 这种方式不需要添加后缀名
        ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
        System.out.println("333333333333----->:"+resourceBundle.getString("name"));
        // 2. 通过InputStream读取文件
        InputStream in3 = new FileInputStream(new File(filePath));
        ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
        System.out.println("333333333333----->:"+resourceBundle2.getString("name"));
        /** 方法四
         *  基于PropertiesConfiguration读取配置文件 需要使用第三方的包
         *
         */

        try {
            Configurations configurations = new Configurations();
            FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
            PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
            System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
            //InputStream in4 = new FileInputStream(new File(filePath));
            PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
            propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
            System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
        } catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
            e.printStackTrace();
        }
    }
}

后记

通常在读取配置文件的时候都是写个工具类,在程序运行的时候就加载配置文件了。这里简单写了一个,凑合着看吧。

package com.xing.test;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PropertiesUtils {

    private static final Log log = LogFactory.getLog(PropertiesUtils.class);

    private static Configurations configurations = null;
    private static PropertiesConfiguration propertiesConfiguration = null;
    private static void initProperties(){
        configurations = new Configurations();
        FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
        try {
            propertiesConfiguration = configurations.properties(PropertiesUtils.class.getClassLoader().getResource("conf/demo.properties"));
        } catch (ConfigurationException e) {
            log.error("配置文件初始化失败",e);
        }
    }
    static {
        initProperties();
    }

    /**
     *  获取String类型的value
     * @param key
     * @return
     */
    public static String getValueString(String key){
        if (propertiesConfiguration == null){
            initProperties();
        }
        return propertiesConfiguration.getString(key);
    }

    /**
     * 获取int类型的value
     * @param key
     * @return
     */
    public static int getValueInt(String key){
        if (propertiesConfiguration == null){
            initProperties();
        }
        return propertiesConfiguration.getInt(key, 0);
    }

}

其实这个包还可以自动重载的功能,修改了配置文件不需要重启服务器即可加载重载配置文件。

点击关注,第一时间了解华为云新鲜技术~

相关文章