[实践总结] Java中读取properties配置文件

读取此key.properties文件

在这里插入图片描述

代码实现

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

public class PropertyUtils {
    
    
    private static final Properties properties = new Properties();

    static {
    
    
        try (InputStream resourceAsStream = PropertyUtils.class.getResourceAsStream("/key.properties")) {
    
    
            properties.load(resourceAsStream);
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
    }

    public static String getKey() {
    
    
        return properties.getProperty("key");
    }

    public static String getValue() {
    
    
        return properties.getProperty("value");
    }
}

UT测试

import org.junit.Assert;
import org.junit.Test;

public class PropertyUtilsTest {
    
    
    @Test
    public void testPropertyUtils() {
    
    
        Assert.assertEquals("key", PropertyUtils.getKey());
        Assert.assertEquals("value", PropertyUtils.getValue());
    }
}

参考

Java中读取properties配置文件的八种方式总结

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/134841597