Pure Java reads the value of the properties configuration file (non-Spring/SrpingBoot way to read)

I am used to using SpringBoot, but I don’t know how to use it without SpringBoot. So specifically record the variable values ​​​​of pure Java reading properties configuration files.

Test test.properties configuration file

params.app="测试"

PropertiesUtils read properties configuration file tool class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * 读取 properties 配置文件工具类
 */
public class PropertiesUtils {
    
    
    /**
     * 私有化构造函数
     */
    private PropertiesUtils(){
    
    }
    /**
     * 路径配置错误会抛出空指针异常
     */
    private static final String TEST_PROPERTIES_URI = "/properties/test.properties";

    /**
     * 获取test.properties
     */
    public static Properties getTestProperties() {
    
    
        Properties props = new Properties();
        InputStream inputStream = PropertiesUtils.class.getResourceAsStream(TEST_PROPERTIES_URI);
        //*.properties配置文件,要使用UTF-8编码,否则会现中文乱码问题
        assert inputStream != null;
        BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        try {
    
    
            props.load(bf);
        } catch (IOException e) {
    
    
//            log.error("读取配置" + TEST_PROPERTIES_URI + "文件异常", e);
            throw new RuntimeException(e);
        }
        return props;
    }

}

Test read properties configuration file

import org.junit.jupiter.api.Test;

import java.util.Properties;

/**
 * 读取properties配置文件
 */
public class ReadPropertiesTests {
    
    

    @Test
    public void test(){
    
    
        Properties testProperties = PropertiesUtils.getTestProperties();
        String param = testProperties.getProperty("params.app");
        System.out.println(param);
    }

}

renderings

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43933728/article/details/131104226