package ss;
/*
对象流的使用:
1,ObjectInputStream 和ObjectOutputStream
作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以
把java中的对象写入到数据源中,也能把对象从数据源中还原回来
*/
import org.junit.Test;
import java.io.*;
public class ObjectInputOutputStreamTest {
/*
序列的过程:将内存中的java对象保存到磁盘当中或者通过网络传出出去。
使用ObjectOutputSteam实现
*/
@Test
void test1() {
ObjectOutput oos = null;
try {
FileOutputStream fos = new FileOutputStream(“/Users/lidonglin/untitled4/src/ss/object.dat”);
oos = new ObjectOutputStream(fos);
String str = new String("我爱北京天安门");
oos.writeObject(str);
oos.flush();
Person per = new Person ("晚风",23,1001,new Person.Account(5000));
oos.writeObject(per);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
反序列化
*/
@Test
public void test2(){
ObjectInputStream ois = null;
try {
FileInputStream fis = new FileInputStream("/Users/lidonglin/untitled4/src/ss/object.dat");
ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
Person p = (Person) ois.readObject();
System.out.println(p);
System.out.println(obj);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package ss;
/*
Person需要满足如下的要求:方可序列化
1,需要实现接口:Serializable;
2.当前类提供一个全局常量:serialVersionUID
3。除了当前Person类需要实现Serialixable接口之外,还必须保证
内部所有属性也必须是可序列化的(默认基本类型可序列化)
*/
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID = 1231242142L;
private String name;
private int age;
private int id;
private Account acct;
public Person(String name, int age, int id, Account acct) {
this.name = name;
this.age = age;
this.id = id;
this.acct = acct;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
", acct=" + acct +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public void setAcct(Account acct) {
this.acct = acct;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
public Account getAcct() {
return acct;
}
static class Account implements Serializable{
public static final long serialVersionUID = 1231343442142L;
private double balance;
public Account(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
'}';
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
}