package stream;
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;
import javax.security.auth.login.AccountException;
import org.junit.jupiter.api.Test;/** 对象流
* 用与存储和读取基本数据类型数据 或 对象的处理刘。它的强大之处就是可以把java中的对象转换成流
*
**/
public classObjectInputStreamTeat {/** 序列化过程:将内存中的java对象保存到磁盘或通过网络传输出去
* 使用ObjectOutputStream
**/@Testpublic voidtestObjectOutputStream() {
ObjectOutputStream oos= null;try{
oos= new ObjectOutputStream(new FileOutputStream("Hello3.txt"));
oos.writeObject(new String("我是中国人"));
oos.flush();
oos.writeObject(new Person("zsben",1,new Account(2000)));
oos.flush();
}catch(Exception e) {
e.printStackTrace();
}finally{try{if(oos!=null)
oos.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}/** 反序列化:用ObjectInputStream实现
**/@Testpublic voidtestObjectInputStream() {
ObjectInputStream ois= null;try{
ois= new ObjectInputStream(new FileInputStream("Hello3.txt"));
Objectobject =ois.readObject();
Stringstring = (String)object;
System.out.println(string);
Object object2=ois.readObject();
Person person=(Person)object2;
System.out.println(person);
}catch(Exception e) {
e.printStackTrace();
}finally{try{if(ois!=null)
ois.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}/** 1.Person类要实现可序列化,必须实现可序列化接口Serializable
* 2.还需要添加一个最终类属性UID
* 3.除了当前Person类需要实现Serializable,还要保证其内部所有属性都是可序列化的
* (默认情况下基本数据类型为可序列化)
* 对象流不能序列化static 和transient修饰的成员
**/
classPerson implements Serializable{public static final long serivalVersionUID = 5432146546351568416L;privateString name;private static intage;privateAccount account;
@OverridepublicString toString() {return "Person [name=" + name + ", age=" + age + ", account=" + account + "]";
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}public Person(String name, intage) {
super();this.name =name;this.age =age;
}public Person(String name, intage, Account account) {
super();this.name =name;this.age =age;this.account =account;
}publicPerson() {
super();
}
}classAccount implements Serializable{private doublebalance;static final public long serivalVersionUID = 54685237864535874L;
@OverridepublicString toString() {return "Account [balance=" + balance + "]";
}public doublegetBalance() {returnbalance;
}public void setBalance(doublebalance) {this.balance =balance;
}public Account(doublebalance) {
super();this.balance =balance;
}publicAccount() {
super();
}
}