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

关于Java中的*.properties的操作

2014-04-04 15:29 417 查看
只给出具体代码,觉得有用的可以参考一下

/**
* 流处理工具类
* @author Shmily
*/
public class StreamUtils {
private static Logger logger = Logger.getLogger(StreamUtils.class);
/**
* 将配置文件*。properties直接转换为Java对象
* @param proPath 配置文件路径
* @return java.util.Properties or null
*/
public static Properties loadProperty(String proPath){
Properties temp=new Properties();
InputStream in= StreamUtils.class.getResourceAsStream(proPath);
try {
temp.load(in);
in.close();
return temp;
} catch (Exception e) {
logger.warn("文件加载失败");
return null;
}
}
/**
* 修改属性文件的值
* @param proPath 属性文件的路径
* @param key
* @param value
* @return 是否修改成功
*/
public static boolean updateProperty(String proPath,String key,String value){
Properties temp=loadProperty(proPath);
if(temp!=null){
//修改值
temp.setProperty(key, value);
try {
File f=new File(String.class.getResource(proPath).toURI().getPath());
OutputStream out=new FileOutputStream(f);
//保存更新
temp.store(out, "update");
f=null;
out.flush();
out.close();
} catch (Exception e) {
logger.error("属性更新失败");
}
return true;
}else{
logger.error("文件加载失败");
return false;
}
}
/**
* 删除特定key
* @param proPath 属性文件的路径
* @param key
* @return 是否删除成功
*/
public static boolean updateProperty(String proPath,String key){
Properties temp=loadProperty(proPath);
if(temp!=null){
temp.remove(key);
try {
FileOutputStream out=new FileOutputStream(new File(String.class.getResource(proPath).toURI().getPath()));
//保存更新
temp.store(out, "update");
temp=null;
out.flush();
out.close();
} catch (Exception e) {
logger.error("属性更新失败");
}
return true;
}else{
logger.error("文件加载失败");
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: