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();
}
}
Object序列化和反序列化
最新推荐文章于 2018-10-14 09:10:21 发布