您的位置:首页 > 其它

读取配置文件中的数据

2010-06-08 17:04 295 查看
在java中有时候会将一些数据放在配置文件中,每次使用的时候进行读取。

1.工具类,获取配置文件。

package com.stduy.Util;

import java.io.FileInputStream;
import java.util.Properties;

/**
* 读配置文件中的数据
*
*/
public class PropertyUtil {

/**
* 得到配置文件对象
*/
private static Properties getProperty() {
Properties property;
try {
String context;
if (isLinux()) {
context = PropertyUtil.class.getClassLoader().getResource("/")
.getFile();
} else {
context = PropertyUtil.class.getClassLoader().getResource("")
.getFile();
}
FileInputStream inputFile = new FileInputStream(context
+ "data.properties");
property = new Properties();
property.load(inputFile);
inputFile.close();

} catch (Exception e) {
e.printStackTrace();
return null;
}
return property;
}

/**
* 根据属性名称读取属性值
*/
public static String getPeopertyValueByName(String name) {
String value = null;
value = getProperty().getProperty(name);
return value;
}

/**
* 判断操作系统
*/
public static boolean isLinux() {
if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
return false;
} else {
return true;
}
}
}


2.类中调用直接一句话就可以了,$(name)配置文件中的属性名

PropertyUtil.getPeopertyValueByName("$(name)");

3.配置文件为data.properties,内容格式为 $(name) = $(value)

如 name = China

不用加标点,属性值取当前行 “=” 后面的内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐