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

java读取properties文件

2015-08-30 12:52 567 查看
创建PropUtil类

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

public class PropUtil {
/**
* 获取config文件
* @param
* @return
*/
private static Properties properties = null;

public PropUtil(String path) {
initialize(path);
}

private void initialize(String path) {
InputStream is = getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {

return;
}
properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {

} finally {
try {
if (is != null)
is.close();
} catch (Exception e) {

}
}
}

/**
* get specified key in config files
*
* @param key
*            the key name to get value
*/
public String get(String key) {
String keyValue = null;
if (properties.containsKey(key)) {
keyValue = (String) properties.get(key);
}
return keyValue;
}
}


创建Properties文件FrameWork.properties

name=linchaojiang
age=29
code=009045


创建测试类ReadFrameWorkProperties ,读取FrameWork.properties文件

public class ReadFrameWorkProperties {

private static PropUtil PropUtil = new PropUtil(
"config/FrameWork.properties");
public static String name = PropUtil.get("name");

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(name);
System.out.println(age);
System.out.println(code);
}

}


输出结果:

linchaojiang

29

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