properties文件配置數據

在代碼中有些項目是要變的,最好配置在config.properties文件中,方便修改的同時不影響程序。
在WEB-INF下建立config.properties文件,他是以鍵值對的形式存在的

UserName=name
Password=123

然後就是在java文件中讀取到配置文件中的值
比如我們有一個ParameterUtil文件

public class ParameterUtil{

public static String getPara(String para) {
String path = ParameterUtil.class.getResource("/").getPath();
path = path.substring(1, path.indexOf("classes"));
path = path + "config.properties";

Properties property = PropertyUtil.getProperties(path);

return property.getProperty(para);
}
}

[b]注意[/b]:以上生成的路徑不能有空格space,所以文件路徑要去掉空格,比如:tomcat 6就不行,中間的空格要去掉。
PropertyUtil如下:

public class PropertyUtil {
public static String readData(String path, String key) {
Properties props = new Properties();
InputStream in = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
in = new BufferedInputStream(fis);
props.load(in);
fis.close();
in.close();
String value = props.getProperty(key);
props =null;
System.gc();
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static void writeData(String path, String key, String value) {
Properties prop = new Properties();
try {
File file = new File(path);
if (!file.exists())
file.createNewFile();
InputStream fis = new FileInputStream(file);
prop.load(fis);
fis.close();
OutputStream fos = new FileOutputStream(path);
prop.setProperty(key, value);
prop.store(fos, "Update '" + key + "' value");
fos.close();
prop = null;
System.gc();
} catch (IOException e) {
System.err.println("Visit " + path + " for updating " + value
+ " value error");
}
}

public static Map<String, String> getMap(String path) {
Properties props = new Properties();
InputStream in = null;
FileInputStream fis = null;
Map<String, String> map = null;
try {
fis = new FileInputStream(path);
in = new BufferedInputStream(fis);
props.load(in);
fis.close();
in.close();
Set<Object> set = props.keySet();
map = new HashMap<String, String>();
for (Object o : set) {
String tempKey = o.toString();
String value = props.getProperty(tempKey);
map.put(tempKey, value);
}
props = null;
System.gc();
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static Properties getProperties(String path) {
Properties props = new Properties();
InputStream in = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
in = new BufferedInputStream(fis);
props.load(in);
fis.close();
in.close();
System.gc();
return props;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

調用方式如下:ParameterUtil.getPara("UserName")
這樣就完成了參數配置,改起來方便。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章