java 操作配置文件 .properties

2014-11-24 09:44:03 · 作者: · 浏览: 1
package com.dms.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class GetDayRandomNumber {
private Properties prop = new Properties();
private final String path = "pageparam.properties";
private String patha = "";
public GetDayRandomNumber(){
this.getFilePath();
this.loadFile();
}
private void getFilePath(){ //获取配置文件的路径
patha = this.getClass().getClassLoader().getResource("").getPath()+"com/dms/config"+"/"+path;
}
public void loadFile(){//加载文件
FileInputStream in = null;
try {
File file = new File(patha);
in = new FileInputStream(file);
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
throw new ExceptionInInitializerError();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}
public void modifyValue(String key , String value){//修改文件
File file = new File(patha);
prop.setProperty(key, value);
FileOutputStream out;
try {
out = new FileOutputStream(file);
prop.store(out, "");//写入的格式
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getValue(String key) { //直接通过主键获取对应的内容
return prop.getProperty(key);
}
}