您的位置:首页 > 编程语言 > Java开发

【Java】Properties文件的解析

2019-04-17 17:36 671 查看
public abstract class ReadProperties {

public ReadProperties() {}

/**
* 回调函数,由调用者处理
* @param key
* @param value
*/
public abstract void dealKeyAndValue(String key, String value);

/**
* 根据包路径解析
* @param packagePath
* @throws IOException
*/
public void read(String packagePath) throws IOException {
InputStream is = this.getClass().getResourceAsStream(packagePath);
read(is);
}

/**
* 根据文件的绝对路径解析
* @param absolutePath
* @throws IOException
*/
public void readFile(String absolutePath) throws IOException {
read(new File(absolutePath));
}

/**
* 根据{@link File}解析
* @param file
* @throws IOException
*/
public void read(File file) throws IOException {
read(new FileInputStream(file));
}

/**
* 根据{@link InputStream}解析
* @param is
* @throws IOException
*/
public void read(InputStream is) throws IOException {
Properties properties = new Properties();
try {
// Properties文件会出现乱码问题,以UTF-8的方式打开
properties.load(new InputStreamReader(is, "UTF-8"));
Enumeration<Object> keys = properties.keys();

while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = properties.getProperty(key);
properties.get(key);

dealKeyAndValue(key, value);
}
} finally {
is.close();
}
}

}

 

使用:
在src下新建一个test.properties文件如下:

 

执行解析:

public class Test {

public static void main(String[] args) throws Exception {
new ReadProperties() {
@Override
public void dealKeyAndValue(String key, String value) {
System.out.println(key + " = " + value);
}
}.read("/test.properties");;
}

}

 

结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: