Java读取Properties工具类 Java读取Properties工具类

本文使用maven环境搭建,JDK版本建议1.8及以上

配置pom文件

maven默认使用jdk1.5编译代码,由于此配置文件使用到了jdk1.7的 try(){}...写法,所以需要在maven的pom文件中引入如下配置。

    <properties>
        <!-- maven-compiler-plugin 将会使用指定的 JDK 版本将 java 文件编译为 class 文件(针对编译运行环境) -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <!-- maven-compiler-plugin 将会使用指定的 JDK 版本对源代码进行编译(针对编译运行环境) -->
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

可能会遇到的问题:

  • 如果出现了下图所示错误

Java读取Properties工具类
Java读取Properties工具类

请检查idea的配置是否如下图所示(选择8-Lamdbas.....)

Java读取Properties工具类
Java读取Properties工具类

在Resource文件夹下创建properties文件

Java读取Properties工具类
Java读取Properties工具类

下面提供一个properties文件的案例,文件名为aliyunOSS.properties

AccessKey=SSSSSSSSSSSS
AccessKeySecret=XXXXXXXX
Buckets=EEEEEEEEEEEEEEEEEEE
EndPoint=oss-cn-beijing.aliyuncs.com

工具类代码

package cn.rayfoo.util;

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

/**
 * Created by rayfoo@qq.com Luna on 2020/4/15 18:38
 * Description : 读取配置文件工具类
 */
public class PropertiesReader {

    //创建Properties对象
    private static Properties property = new Properties();
    //在静态块中加载资源
    static {
        //使用try(){}.. 获取数据源
        //注意 * 这是jdk1.7开始支持的特性,如果使用的是低版本 需要提升jdk版本 或者更改写法
        try (
                InputStream in = PropertiesReader.class.getResourceAsStream("/aliyunOSS.properties");
        ) {
            property.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字符串类型的值
     * @param key
     * @return
     */
    public static String get(String key) {
        return property.getProperty(key);
    }

    /**
     * 获取Integer类型的值
     * @param key
     * @return
     */
    public static Integer getInteger(String key) {
        String value = get(key);
        return null == value ? null : Integer.valueOf(value);
    }

    /**
     * 获取Boolean类型的值
     * @param key
     * @return
     */
    public static Boolean getBoolean(String key) {
        String value = get(key);
        return null == value ? null : Boolean.valueOf(value);
    }

    /**
     * 设置一个键值对
     * @param key
     * @param value
     */
    public static void set(String key,String value){
        property.setProperty(key,value);
    }

    /**
     * 添加一个键值对
     * @param key
     * @param value
     */
    public static void add(String key,Object value){
        property.put(key,value);
    }
}


测试

package cn.rayfoo;

/**
 * Created by rayfoo@qq.com Luna on 2020/4/15 19:00
 */
public class TestApp {

    public static void main(String[] args) {
        System.out.println(PropertiesReader.get("AccessKey"));
        System.out.println(PropertiesReader.get("AccessKeySecret"));
        System.out.println(PropertiesReader.get("Buckets"));
        System.out.println(PropertiesReader.get("EndPoint"));
    }
}