日期:2014-05-20  浏览次数:20732 次

关于Properties键值对存储小程序
[code=Java][/
//将一个文件中的键值对信息存入到Properties集合中,并且将集合中修改好后的数据再次存入文件中
import java.util.*;
import java.io.*;
class PropertiesDemo1
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("e:"+File.separator+"11.txt");//创建一个输入刘传入load()
=================================================================================
Properties p=new Properties();
p.load(fis);
p.setProperty("stu1","111");//修改内存中的键值对信息,此操作并没有修改源文件
FileOutputStream fos=new FileOutputStream("e:"+File.separator+"11.txt");
p.store(fos,"");//将内存中修改好的内容存入源文件,第二个参数是注释的意思
p.list(System.out);
fis.close();
fos.close();
}
}
]
小弟想问的是为什么将FileOutputStream fos=new FileOutputStream("e:"+File.separator+"11.txt");
这句话放到=============这行的时候,我修改Properties集合里的值时,不会保存在文件里。为什么放在下边才有效?

------解决方案--------------------
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
{
this(name != null ? new File(name) : null, append);
}
源码直接 new File(name)了
不想要覆盖的话用下面这种格式
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.append = append;
if (append) {
openAppend(name);
} else {
open(name);
}
}
会检查是否文件存在,在决定是否创建文件。