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 class ObjectInputStreamTeat { /* * 序列化过程:将内存中的java对象保存到磁盘或通过网络传输出去 * 使用ObjectOutputStream * */ @Test public void testObjectOutputStream() { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("Object.dat")); 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实现 * */ @Test public void testObjectInputStream() { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("Object.dat")); Object object = ois.readObject(); String string = (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修饰的成员 * */ class Person implements Serializable{ public static final long serivalVersionUID = 5432146546351568416L; private String name; private static int age; private Account account; @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", account=" + account + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person(String name, int age, Account account) { super(); this.name = name; this.age = age; this.account = account; } public Person() { super(); } } class Account implements Serializable{ private double balance; static final public long serivalVersionUID = 54685237864535874L; @Override public String toString() { return "Account [balance=" + balance + "]"; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public Account(double balance) { super(); this.balance = balance; } public Account() { super(); } }
1