java代码如何读取properties文件

我们在开发工程中,有时候需要在Java代码中定义一些在部署生产环境时容易改变的变量,还需要我们单独放在一个外部属性文件中,方便我们将来修改。这里列出了两种比较方便的方式。

一、在Spring配置文件中使用 util:properties 标签进行暴露 properties 文件中的内容,需要注意的是需要在Spring的配置文件的头部声明以下部分。

xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"

1. 在classpath路径下新建 config.properties 内容如下:

app.id=appId

2. 修改Spring的配置文件

<util:properties id="appConfig" location="classpath:config.properties"></util:properties>

3. 在需要调用的类中声明全局变量,加上@Value注解

@Value("#{appConfig['app.id']}")
private String appId;

二、使用Java的Properties类

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

/**
 * properties文件获取工具类
 */
public class PropertyUtil {
    
    private static Properties props;
    static {
        loadProps();
    }

    synchronized static private void loadProps(){
        System.out.println("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        try {
            // 第一种,通过类加载器进行获取properties文件流-->
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("db.properties");
            // 第二种,通过类进行获取properties文件流-->
            //in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
            props.load(in);
        } catch (FileNotFoundException e) {
            System.out.println("jdbc.properties文件未找到");
        } catch (IOException e) {
            System.out.println("出现IOException");
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                System.out.println("jdbc.properties文件流关闭出现异常");
            }
        }
        System.out.println("加载properties文件内容完成...........");
        System.out.println("properties文件内容:" + props);
    }

    /**
     * 根据key获取配置文件中的属性
     */
    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    /**
     * 根据key获取配置文件中的属性,当为null时返回指定的默认值
     */
    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}

测试:

String appId = PropertyUtil.getProperty("app.id");
System.out.println("appId = " + appId);
原文地址:https://www.cnblogs.com/libra0920/p/5663373.html