java中properties类中关于store(arg0,arg1)用法的讲解

store 用来给properties添加新的键值对。
API中这样写道:
    
void store(OutputStream out, String comments)
Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.
void store(Writer writer, String comments)
Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.
第一个参数为 OutputStream/Writer 用来指向加载的配置文件, 第二个参数为 String 用来给配置文件添加注释。

 public static void main(String[] args) throws Exception{
  Properties p1=new Properties();
//先写一个匿名FileReader用来加载配置文件123.txt
  p1.load(new FileReader(new File("C:\\123.txt")));
 //给123.txt中添加新的内容 name2=Jack
  p1.setProperty("name2", "Jack");
 
//设置FileWriter时不要给第二个参数true,负责会在原有内容的基础上重写原内容和新内容。
  FileWriter fw=new FileWriter(new File("C:\\123.txt"));
//这里的第二个参数是用来写注释的。在Proterties中的注释是"#"
  p1.store(fw, "the follow is the third try");
 }

123.txt中
以前只有一行是:

    name=Tom

运行后的结果:

#the follow is the third try
#Thu May 17 09:05:22 CST 2018
name=Tom
name2=Jack
可以看到红色字体正是注释的内容。 还有,properties的后缀不只是.properties,像本文的.txt文本后缀的文件同样可用

猜你喜欢

转载自blog.csdn.net/c_1969/article/details/80345829
今日推荐