package com.defshare.foundation.global;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.URLUtil;
/**
* 属性文件读写工具类
* @author jiangtong
*
*/
public class PropertiesUtil {
/**
* <h3>加载属性文件[不支持缓存]</h3>
* @param filename
* @return
*/
public static Properties loadProperties(String filename){
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(URLDecoder.decode(PropertiesUtil.class.getResource("/"+filename).getFile(),"UTF-8")));
properties.load(fis);
return properties;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (fis!=null) fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return properties;
}
/**
* <h3>获得属性文件的某个key值,支持缓存
* @param filename
* @param key
* @return
*/
public static String get(String filename,String key){
ResourceBundle res = ResourceBundle.getBundle(filename.replace(".properties",""));
String value = res.getString(key);
res.clearCache();
return value;
}
/**
* <h3>给属性文件添加或者覆盖键值对</h3>
* @param filename
* @param key
* @param value
*/
public static void set(String filename,String key,String value){
FileWriter fis = null;
try {
Properties properties = loadProperties(filename);
properties.setProperty(key, value);
fis = new FileWriter(URLDecoder.decode(PropertiesUtil.class.getResource("/").getPath(),"UTF-8")+filename,false);
properties.store(fis,"");
properties.clear();
fis.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fis!=null)
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
简单的属性文件读写工具类
最新推荐文章于 2021-05-25 18:04:07 发布