Java读取和修改properties文件
方法说明:
1.Properties getProperties(String filepath):根据路径读取属性文件,返回Properties类;
2.void SaveProperties(Properties prop,String filepath):保存属性到指定路径(如果文件不存在,请先创建File);
3.String getConfigValue(String key):获取指定Key的属性;
4.void setConfigValue(String key,String value):设置指定Key的属性值。
其中方法3,4调用的属性文件为默认的文件,文件名和路径通过CONFIG和LOCATION设置,该文件的位置为工程中的src下,导出jar文件的同级目录下(LOCATION获取)。
下面代码:
public class PropUtils { public static String LOCATION; public static final String CONFIG = "config.properties"; static{ try { String temp = URLDecoder.decode(PropUtils.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); LOCATION = temp.substring(1, temp.lastIndexOf('/')); } catch (UnsupportedEncodingException e) { LOCATION = ""; } } /** * @param args * @throws Exception */ public static Properties getProperties(String filepath) throws Exception { Properties prop = new Properties(); FileInputStream fis = new FileInputStream(LOCATION+"/"+filepath); prop.load(fis); return prop; } public static void SaveProperties(Properties prop,String filepath) throws Exception { FileOutputStream fos = new FileOutputStream(LOCATION+"/"+filepath); prop.store(fos, "@author Isea533"); fos.close(); } public static String getConfigValue(String key) { try { Properties properties = getProperties(CONFIG); if(properties.get(key)!=null){ return properties.get(key).toString(); } } catch (Exception e) { System.out.println(e.getMessage()); } return ""; } public static void setConfigValue(String key,String value){ try { Properties properties = getProperties(CONFIG); properties.setProperty(key, value); SaveProperties(properties, CONFIG); } catch (Exception e) { System.out.println(e.getMessage()); } } }