Object序列化和反序列化

package com.zyf.day22;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Address implements Serializable{
	String country;
	String city;
	public Address(String country,String city) {
		// TODO Auto-generated constructor stub
	    this.country = country;
	    this.city = city;
	}
}
class User implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String userName;
	String password;
	transient int age;
	Address address;
	public User(String userName,String password,int age,Address address){
		this.userName = userName;
		this.password = password;
		this.age = age;
		this.address = address;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "用户名:" + this.userName + "密码:" + this.password + "年龄: " + this.age + "地址: " + this.address;
	}
}
public class demo3 {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//writeObj();
		readObj();

	}
	//把文件中的对象信息读取出来--------------》对象的反序列化
	public static void readObj() throws IOException, ClassNotFoundException{
		//find file
		File file = new File("c:\\a.txt");
		//建立数据的输入通道
		FileInputStream fileInputStream = new FileInputStream(file);
		//建立对象输入流对象
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
		//读取对象信息
		User user = (User) objectInputStream.readObject();
		System.out.println("对象User信息= " + user);
		
	}
	//定义方法把对象的信息写到硬盘上
	public static void writeObj() throws IOException{
		Address address = new Address("中国","广州");
		//把user对象的信息持久化存储
        User user = new User("admin","123",14,address);
        //找到目标文件
        File file = new File("c:\\a.txt");
        //建立数据输出流对象
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        //建立对象的输出对象
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        //把对象写出
        objectOutputStream.writeObject(user);
        //关闭资源
        objectOutputStream.close();
        
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值