在项目开发中,经常会把一些可能变化的量配置在.properties文件中,这样当需要修改时只需修改配置文件中的值即可,不用修改java代码,便于后期维护,那么问题来了怎样在java代码中读取配置文件中的属性值呢?下面给出解决办法
1.准备一个.properties的配置文件,为了演示方便这里只给出一个属性值
2.编写读取配置文件属性值的java类(为演示方便未加日志,实际开发中需加上)
package com.properties;
import java.io.IOException;
import java.util.Properties;
public class PropertiesTest {
private static Properties properties = new Properties();
static {
try {
// 1.加载conf.properties配置文件
properties.load(PropertiesTest.class.getClassLoader()
.getResourceAsStream("conf.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 2.读取配置文件中的属性值
String address = properties.getProperty("address");
// 3.在控制台中打印出取出的值
System.out.println(address);
}
}
执行一下看一下结果
OK,大功告成控制台显示取出的属性值正确,如果有其他属性值可以按照相同的方式取.