package cn.itcast.other;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
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){
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 passwrod) {
this.userName = userName;
this.password = passwrod;
}
public User(String userName , String passwrod,int age,Address address) {
this.userName = userName;
this.password = passwrod;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "用户名:"+this.userName+ " 密码:"+ this.password+" 年龄:"+this.age+" 地址:"+this.address.city;
}
}
public class Demo3 {
public static void main(String[] args) throws IOException, Exception {
writeObj();
}
public static void readObj() throws IOException, ClassNotFoundException{
File file = new File("F:\\obj.txt");
FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
User user = (User) objectInputStream.readObject();
System.out.println("对象的信息:"+ user);
}
public static void writeObj() throws IOException{
Address address = new Address("中国","广州");
User user = new User("admin","123",15,address);
File file = new File("F:\\obj.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(user);
objectOutputStream.close();
}
}