网上看到问题,收集起来:
基于java.util.Properties类写了一个修改属性文件的方法。测试的时候发现,该方法可以修改文件指定key的value,但是除了修改的key和value外,其他的内容全部被清除了,请问为何。。代码如下
/**
* 新增或修改资源文件的内容
*
* @param resourceFile
* 资源文件(绝对路径+文件名,不需要.properties后缀)
* @param key 键
* @param value 值
*/
public static void setString(String resourceFile, String key, String value){
Properties prop = new Properties();
try {
if(resourceFile.indexOf(".properties")==-1){
resourceFile+=".properties";
}
FileInputStream fis = new FileInputStream(resourceFile);
FileOutputStream fos = new FileOutputStream(resourceFile);
try {
prop.load(fis);
fis.close();
prop.setProperty(key, value);
prop.store(fos, "Copyright Thcic");
fos.close();
} catch (IOException e) {
e.printStackTrace();
log.error("修改资源文件:"+resourceFile+"异常!msg:"+e.getMessage());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("无法获得资源文件:" + resourceFile);
}
}
答案:
FileOutputStream fos=new FileOutputStream(resourceFile);运行时会马上覆盖掉原有的内容,因此你这句话应该移到将键值对载入完成后。
修改如下,测试通过。
/**
* 新增或修改资源文件的内容
*
* @param resourceFile
* 资源文件(绝对路径+文件名,不需要.properties后缀)
* @param key 键
* @param value 值
*/
public static void setString(String resourceFile, String key, String value){
Properties prop = new Properties();
try {
if(resourceFile.indexOf(".properties")==-1){
resourceFile+=".properties";
}
FileInputStream fis = new FileInputStream(resourceFile);
try {
prop.load(fis);
fis.close();
prop.setProperty(key, value);
FileOutputStream fos = new FileOutputStream(resourceFile);
prop.store(fos, "Copyright Thcic");
fos.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("修改资源文件:"+resourceFile+"异常!msg:"+e.getMessage());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("无法获得资源文件:" + resourceFile);
}
}