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

jsp中操作java属性文件

2011-05-13 21:47 295 查看
写一个操作属性文件的类,从网上找的一个别人写的类:

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

public class SetProperties {

/**
* 对属性文件(xx.properties)的操作
**/
public SetProperties() {
}

/**
* 采用Properties类取得属性文件对应值
*
* @parampropertiesFileNameproperties文件名,如a.properties
* @parampropertyName属性名
* @return根据属性名得到的属性值,如没有返回""
*/
public String getProperties(String propertiesFileName,
String propertyName) {
String s = "";
Properties p = new Properties();// 加载属性文件读取类
FileInputStream in;
try {
// propertiesFileName如test.properties
in = new FileInputStream(propertiesFileName);// 以流的形式读入属性文件
p.load(in);// 属性文件将该流加入的可被读取的属性中
in.close();// 读完了关闭
s = p.getProperty(propertyName);// 取得对应的属性值
} catch (Exception e) {
e.printStackTrace();
}
return s;
}

/**
* 更改属性文件的值,如果对应的属性不存在,则自动增加该属性
*
* @parampropertiesFileNameproperties文件名,如a.properties
* @parampropertyName属性名
* @parampropertyValue将属性名更改成该属性值
* @return是否操作成功
*/
public boolean setProperties(String propertiesFileName,
String propertyName, String propertyValue) {
boolean writeOK = true;
Properties p = new Properties();
FileInputStream in;
try {
in = new FileInputStream(propertiesFileName);
p.load(in);//
in.close();
p.setProperty(propertyName, propertyValue);// 设置属性值,如不属性不存在新建
// p.setProperty("testProperty","testPropertyValue");
FileOutputStream out = new FileOutputStream(propertiesFileName);// 输出流
p.store(out, "");// 设置属性头,如不想设置,请把后面一个用""替换掉
out.flush();// 清空缓存,写入磁盘
out.close();// 关闭输出流
} catch (Exception e) {
e.printStackTrace();
}
return writeOK;

}
}


 

部署的时候将属性文件放到工程的根目录下(方便操作),在servlet或Action中操作如下:

 

SetProperties sp = new SetProperties();

//获得系统的文件分隔符,Windows是“/”, Unix是“/”
String se = System.getProperty("file.separator");

//获得web跟目录的绝对路径
String str = request.getSession().getServletContext().getRealPath(se);

//操作
System.out.println(sp.getProperties(str + "db.properties", "DBDriver"));
sp.setProperties(str + "db.properties", "DBUrl", "new URL");
sp.setProperties(str + "db.properties", "DBUser", "new User");
System.out.println(sp.getProperties(str + "db.properties", "DBUrl"));
System.out.println(sp.getProperties(str + "db.properties", "DBUser"));


 

 

最关键的是路径要写对。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息