在应用程序中,经常需要读取配置文件。Java默认配置文件是以 .properties
为扩展名,每行以 key=value
表示,以 #
开头的是注释。以下是一个配置文件:
#prop.properties
last_open_file=/data/hello.txt
auto_save_interval=60
读取配置文件
我们可以编写一个propertiesUtil
工具类:
public class PropertiesUtil {
//通过key获取properties中的值
public static String getValue(String key) throws IOException {
Properties properties = new Properties();
properties.load(new PropertiesUtil().getClass().getResourceAsStream("/prop.properties"));
return properties.getProperty(key);
}
//通过path、key获取properties中的值
public static String getValue(String path, String key) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(path));
return properties.getProperty(key);
}
}
下面进行测试:
@Test
public void m7() throws IOException {
System.out.println(PropertiesUtil.getValue("auto_save_interval"));
System.out.println(PropertiesUtil.getValue("/Users/yanjundong/Desktop/setting.properties","path"));
}
//输出结果
60
d:/database
上面测试代码中的
/Users/yanjundong/Desktop/setting.properties
是放入桌面上的另一个配置文件,需要注意的是,如果有多个.properties
文件,可以反复调用load()
读取,后面读取的key-value
会覆盖已读取的key-value
。