Properties配置文件读取工具类
import java.io.*;
import java.util.*;
public class ResourceUtils {
private static final String defaultResourceFile = "application";
private static Map<String, ResourceBundle> bundles = new HashMap<String, ResourceBundle>();
private static Map<String,Map<String,String>> resource = new HashMap<String, Map<String,String>>();
private static void loadResourceBundle(String resourceFile) {
ResourceBundle bundle = ResourceBundle.getBundle(resourceFile);
bundles.put(resourceFile, bundle);
}
public static final String getConfigByName(String name) {
return getConfigByName(name,defaultResourceFile);
}
public static final String getConfigByName(String name, String resourceFile) {
if (bundles.get(resourceFile) == null) {
loadResourceBundle(resourceFile);
}
ResourceBundle bundle = bundles.get(resourceFile);
if(bundle.containsKey(name)){
try {
return new String(bundle.getString(name).getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return name;
}
public static Map<String,String> getAll(String resourceFile) throws Exception{
if (bundles.get(resourceFile) == null) {
loadResourceBundle(resourceFile);
}
if(resource.get(resourceFile) ==null){
loadResource(resourceFile);
}
return resource.get(resourceFile);
}
public static void loadResource(String resourceFile) throws Exception{
Map<String,String> result = new LinkedHashMap<String, String>();
Properties properties = new Properties();
InputStream inputStream = ResourceUtils.class.getClassLoader().getResourceAsStream(resourceFile+".properties");
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
properties.load(bf);
Set<Object> keys = properties.keySet();
for(Object key:keys){
result.put(key.toString(), properties.get(key).toString());
}
} catch (IOException e) {
e.printStackTrace();
}finally{
inputStream.close();
}
resource.put(resourceFile, result);
}
public static void putValueByKey(String key,String value,String path)throws Exception{
InputStream inputStream = null;
OutputStream outputStream = null;
try {
Properties props = new Properties();
System.out.println(path);
inputStream = new FileInputStream(path);
props.load(inputStream);
props.setProperty(key, value);
outputStream = new FileOutputStream(path);
props.store(outputStream, "Update " + key );
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
inputStream.close();
outputStream.close();
}
}
}