对象流_序列化反序列化

注意 进行序列化的对象必须继承ava.io.Serializable 接口
代码
class Employee implements java.io.Serializable{//数据的封装 进行序列化的对象必须继承ava.io.Serializable 接口

	private transient String name;//transient 表示该数据不需要序列化
	private int salary;
	public Employee(String name, int salary) {//构造器 快捷键 alt+shift+s constructor using fields

		this.name = name;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException  {
	ByteArrayOutputStream os = new 		ByteArrayOutputStream();//字节数组流
		 ObjectOutputStream ois = new ObjectOutputStream(new BufferedOutputStream(os));	//对象流+缓冲流

		//操作数据类型+数据
			ois.writeBoolean(false);
			ois.writeUTF("打了代码有多愁,头发掉了一头又一头");
			ois.writeUTF("测试2");
			
		//对象
			Employee employee =new Employee("乔哥", 999);
			ois.writeObject(employee);
			ois.flush();//不要忘了
		byte [] len =os.toByteArray();
		ByteArrayInputStream in = new ByteArrayInputStream(len);
	
		ObjectInputStream ins = new ObjectInputStream(new BufferedInputStream(in));
		
			boolean i=ins.readBoolean();
			String o=ins.readUTF();
			String u =ins.readUTF();
			
			Object str =ins.readObject();
			if(str instanceof Employee) {//对象的输出用这种格式
				Employee s =(Employee)str;
				System.out.println(s.getName()+s.getSalary());
			}
			System.out.println(i+o+u);
}
发布了27 篇原创文章 · 获赞 5 · 访问量 647

猜你喜欢

转载自blog.csdn.net/qq_44620773/article/details/104028169