public class LearnProperties {
public static void main(String[] args) throws IOException{
Properties prop = new Properties();
FileInputStream fi = new FileInputStream("E:\\mycode\\java\\learningJava\\src\\learnJava\\learn.properties");
//FileOutputStream fo = new FileOutputStream("E:\\mycode\\java\\learningJava\\src\\learnJava\\learn.properties");
prop.load(fi);
System.out.println("name: " + prop.getProperty("name"));
System.out.println("age: " + prop.getProperty("age", "18"));
//若配置文件中为有salary这个key,则返回默认值18w
System.out.println("salary: " + prop.getProperty("salary", "18w"));
FileOutputStream fo = new FileOutputStream("E:\\mycode\\java\\learningJava\\src\\learnJava\\learn.properties");
prop.setProperty("salary", "5 yuan");
//保存回配置文件中
prop.store(fo,"");
Properties prop2 = new Properties();
prop2.load(fi);
System.out.println("salary: " + prop2.getProperty("salary", "18w"));
fo.close();
}
}
FileOutputStream不要紧接着FileInputStream定义,这样会覆盖掉FileInputStream,导致加载到prop中的内容是空
Properties可以方便的对配置文件进行读写操作
配置文件格式为key=value形式,如下为一个配置文件内容
age=22
name=zxye
以等号划分。
Properties类实现了HashTable接口,因此,在Proterties中的key-value是以Hash形式存储起来。
最后输出结果
name: zxye
age: 22
salary: 18w
salary: 5 yuan
参考: http://blog.csdn.net/qinpeng100423/article/details/9125857