类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
已有一个配置文件:property.txt
格式:
name=1
age=12
sex=male
要修改其中一个配置:
eg. age=100
希望得到的property.txt为:
name=1
age=100
sex=male
请问大侠怎么做,最好能给个简单的代码看看
这是我写的用于修改配置值的方法代码:
代码:
static void updateConfigureValue(String targetFile, String parameterName, String parameterValue)
{
Properties prop = new Properties();
try {
fis = new FileInputStream(targetFile);
fos = new FileOutputStream(targetFile);
prop.load(fis);
prop.setProperty(parameterName, parameterValue);
prop.store(fos, "Update " + parameterName + " value");
}
catch (IOException e) {
System.out.println("Visit " + targetFile + " for updating " +parameterName + "
value error");
}
问题是,由于fis和fos都指向了同一个文件,所以最后得到的property.txt成了这样的:
age=100
该怎么解决???
网友回答:
prop.load(fis); //仅仅是读取而已
prop.setProperty(parameterName, parameterValue); //只有set了age的parameterName, parameterValue
这是正确的
用个循环,把别的原封不到的写进去。
把 fos = new FileOutputStream(targetFile); 放到 load 后面去。
public static void updateConfigureValue(String targetFile,
String parameterName, String parameterValue) {
Properties prop = new Properties();
try {
FileInputStream fis = new FileInputStream(targetFile);
prop.load(fis);
fis.close();
prop.setProperty(parameterName, parameterValue);
FileOutputStream fos = new FileOutputStream(targetFile);
prop.store(fos, "Update " + parameterName + " value");
fos.close();
} catch (IOException e) {
System.out.println("Visit " + targetFile + " for updating "
+ parameterName + "value error");
}
}
原因,用 FileOutputStream 打开一个文件准备写入内容时,已经是新创建的一个文件,文件内容已经被清空,所以你读不出来东西。
先读再写。你读的时候就准备写了。
fis = new FileInputStream(targetFile);
fos = new FileOutputStream(targetFile);