序列化和反序列 properties

在Java语言中,将对象序列化,存储到文件中,要实现这一过程,其类要实现序列化接口,我们拿学生类为例:

public class Student implements Serializable{
	private static final long serialVersionUID = 1L;//生成版本序列号
	private String name;
	private String ID;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getID() {
		return ID;
	}
	public void setID(String iD) {
		ID = iD;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return " [name=" + name + ", ID=" + ID + ", sex=" + sex + "]";
	}
}
实现序列化实例:

public static void main(String[] args) throws IOException, IOException {
		Student student=new Student();
		student.setName("小明");
		student.setID("201405251");
		student.setSex("男");
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("aa.txt"));
		oos.writeObject(student);
		oos.close();
	}
实现反序列化,读取文件中的数据:

public static void main(String[] args) throws IOException, IOException, ClassNotFoundException {
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream("aa.txt"));
		Student student=(Student) ois.readObject();
		System.out.println(student);
	}
properties在Java中大多是对配置文件的读写吧,通过键值对存取:

public static void main(String[] args) throws IOException, IOException {
		Properties properties=new Properties();
		properties.setProperty("name", "小明");
		properties.setProperty("sex", "男");
		properties.store(new FileOutputStream("bb.properties"),null);
	}
从文件中读取时:

public static void main(String[] args) throws IOException, IOException {
		Properties properties=new Properties();
		properties.load(new FileInputStream("bb.properties"));
		System.out.println("name  "+properties.getProperty("name"));
		System.out.println("sex   "+properties.getProperty("sex"));






猜你喜欢

转载自blog.csdn.net/qq_34447328/article/details/51996051