序列化代码:
package cn.tedu.properties;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo1 {
public static void main(String[] args) throws IOException {
//创建Properties映射类得对象
Properties p=new Properties();
//往映射对象中添加元素—键值对
p.setProperty(“name”,“lili”);
p.setProperty(“age”,“10”);
p.setProperty(“gender”,“女”);
//p.setProperty(null,null);不可以
//把映射对象中的内容持久化到一个properties文件里
//一定要写在.properties的文件
p.store(new FileOutputStream
(“p.properties”),“这是我朋友!!!”);
}
}
反序列化代码:
package cn.tedu.properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo2 {
public static void main(String[] args) throws IOException {
//创建映射类对象
Properties p=new Properties();
//反序列化----读取文件内容—把获取的内容放到映射对象身上
p.load(new FileInputStream(“p.properties”));
//根据对象身上键获取值
System.out.println(p.getProperty(“gender”));
//如果给定的键不存在返回的就是null
//如果返回的值是null,表明键不存在
/* System.out.println(p.getProperty(“ame”));
System.out.println(p.getProperty(“age”));*/
//列出映射信息—文件信息
p.list(System.out);
}
}
输出:
女
– listing properties –
age=10
name=lili
gender=女
序列化代码图:反序列化代码图:
输出: