81,091
社区成员
发帖
与我相关
我的任务
分享
import java.util.Locale;
import java.util.ResourceBundle;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
* @author 螃蟹
*/
public class GetProperties {
private ResourceBundle bundle = null;
private String proName = "";
public GetProperties(String proname) {
this.proName = proname;
}
/**
* 按照KEY获取配置文件中相应值
*
* @param type
* @return 取其中的属性值(String类型)
*/
public String getProp(String type) throws Exception {
if (bundle == null) {
try {
bundle = ResourceBundle.getBundle(this.proName, Locale.getDefault());
} catch (Exception e) {
System.out.println("获取资源出错!" + e);
}
}
return bundle.getString(type);
}
// 属性文件的路径
String profilepath = Thread.currentThread().getContextClassLoader().getResource("dictionary.properties").toString();
public Properties props = new Properties();
public String init(String str, String val) {
try {
if (profilepath.indexOf("file:") != -1) {
profilepath = profilepath.replaceFirst("file:", "");
}
props.load(new FileInputStream(profilepath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
return updateProperties(str, val);
}
/**
* 更新properties文件的键值对 如果该主键已经存在,更新该主键的值; 如果该主键不存在,则插件一对键值。
*
* @param keyname
* 键名
* @param keyvalue
* 键值
*/
public String updateProperties(String keyname, String keyvalue) {
try {
if (profilepath.indexOf("file:") != -1) {
profilepath = profilepath.replaceFirst("file:", "");
}
props.load(new FileInputStream(profilepath));
// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream fos = new FileOutputStream(profilepath);
props.setProperty(keyname, keyvalue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
props.store(fos, "Update '" + keyname + "' value");
} catch (IOException e) {
System.err.println("属性文件更新错误");
}
return "success";
}
// 测试代码
public static void main(String[] args) {
// /dictionary.properties
// String s=System.getProperty("user.dir");
// System.out.println("==>"+Thread.currentThread().getContextClassLoader().getResource("dictionary.properties"));
// gp.updateProperties("test", "tanglong8848");
// System.out.println("操作完成");
}
}