1.对文件的读
1.1创建一个Properties对象
Properties myproperties = new Properties();
1.2加载文件信息,有两种方法,一种是用文件流读取,一种是用读文件流提取
myProperties = new Properties();Class s = null;try {//s = Class.forName("com.common.SystemConfig");//InputStream is = s.getResourceAsStream(systemConfigPath);
FileInputStream is = new FileInputStream(systemConfigPath);
myProperties.load(is);
is.close();
} catch (IOException e) {
e.printStackTrace(); }
1.3想要读去myProperties中的属性,只需要调用myProperties.getProperty(key);就可以调用。
2.对文件的写
在对文件进行写的时候发现一个问题,如果的获取写文件流向下面的格式的话(跟读文件的文件路径一样)那么你会发现在读取值的时候已经修改了。但是Properties文件中的key-value值对还是没有改变,(本人觉得是因为写文件流所需要的文件路径是绝对路径,那么你就要把路径写完整,就可以在改变Properties的属性值的时候,就写如文件中) FileOutputStream fos = new FileOutputStream(systemConfigPath);
正确的路径
FileOutputStream fos = new FileOutputStream("src/resource"+systemConfigPath);
public static void setSystemParam(String param,String value){
try {
myProperties.setProperty(param, value);
FileOutputStream fos = new FileOutputStream("src/resource"+systemConfigPath);
myProperties.store(fos,null);
fos.flush();//这个很重要,不刷新的话每次调用该方法,上次的输入还是被保存,所以要清除缓存
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}