Java 对象的序列化与反序列化

package cn.itcast.objiecttest.demo;
/**
 * 对象的序列化与反序列化
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.itcast.objiectperson.demo.Person;

public class TestObjectDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
//		putobject();
		
		getobject();
	}

	public static void getobject() throws ClassNotFoundException, IOException {
		
		ObjectInputStream obj=new ObjectInputStream(new FileInputStream("1.objiect"));
		Person p=(Person)obj.readObject();
		System.out.println(p.getName()+":"+p.getAge());
		obj.close();
	}

	public static void putobject() throws IOException {
		
		ObjectOutputStream obj=new ObjectOutputStream(new FileOutputStream("1.objiect"));
		obj.writeObject(new Person("哈哈", 30));
		obj.close();
	}
}

person类:

package cn.itcast.objiectperson.demo;

import java.io.Serializable;
//对对象进行序列化,对象必须实现Serializable接口
public class Person implements Serializable {
    private static final long serialVersionUID = 1315L;
	private String name;
	private int age;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

猜你喜欢

转载自blog.csdn.net/TDOA1024/article/details/82705687