java IO 对象流 反序列化和序列化

例:

 重点:需要序列化的对象必须实现Serializable接口

//需要序列化的对象 
public class User implements Serializable {
	private String name;
	private String password;
	private int age;
	
	public User(String name, String password, int age) {
		this.name = name;
		this.password = password;
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", password=" + password + ", age=" + age + "]";
	}
}
//使用对象流来实现序列化和反序列化	
public class ObjectInputStreamAndObjectOutputStreamDemo {
	private static File file;

	public static void main(String[] args) throws Exception {
		 file=new File("file/obj.txt");
		writerObject();
		readerObject();
	}
     //反序列化操作
	private static void readerObject() throws Exception{
		ObjectInputStream in =new ObjectInputStream(new FileInputStream(file));
		Object content=in.readObject();
		System.out.println(content);
		in.close();
	}
	//序列化操作
	private static void writerObject() throws Exception {
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(file));
		out.writeObject(new User("张三","123456",17));
		out.close();
		
	}
}

 

原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6723475.html