Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件.
## 配置文件
配置文件对于程序是很重要的,为程序的维护带来了很大的便利性
>在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
Properties类继承自Hashtable,Java 集合系列11之 Hashtable详细介绍(源码解析)和使用示例 - 如果天空不死 - 博客园
它提供了几个主要的方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
app.properties文件
appname=learnJava
basepackage=com.oneboi
读取配置的辅助文件
package com.oneboi;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropsUtil {
/**
* 加载配置文件
*
* @param fileName 配置文件名
* @return
*/
public static Properties loadProps(String fileName) {
Properties props = null;
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (is == null) {
throw new FileNotFoundException(fileName + " file is not found");
}
props = new Properties();
props.load(is);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return props;
}
/**
* 获取字符型属性(默认值为空字符串)
*
* @param props
* @param key
* @return
*/
public static String getString(Properties props, String key) {
return getString(props, key, "");
}
/**
* 获取字符型属性(可指定默认值)
*
* @param props
* @param key
* @param defaultValue
* @return
*/
public static String getString(Properties props, String key, String defaultValue) {
String value = defaultValue;
if (props.containsKey(key)) {
value = props.getProperty(key);
}
return value;
}
}
测试类
package com.oneboi;
import java.io.FileNotFoundException;
import java.util.Properties;
public class Test {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
Properties in =PropsUtil.loadProps("app.properties");
String appname= PropsUtil.getString(in,"appname");
System.out.println(appname);
}
}
转自:https://zhuanlan.zhihu.com/p/39835413