Object流:直接将Object流写入或读出。
- TestObjectIO.java
- transient关键字(英文名:透明的,可以用来修饰成员变量(实例变量),transient修饰的成员变量(实例变量)在serializable序列化时不予考虑)
- serializable接口(可以被序列化,属于标记性接口,里面没有定义方法,打标机给编译器看,编译器看到了则认为该类可以被序列化)
- externalizable接口
1 package com.zyjhandsome.io; 2 3 import java.io.*; 4 5 public class TestObjectIO { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 T t = new T(); 10 t.k = 8; 11 12 try { 13 FileOutputStream fos = new FileOutputStream("D:\zhaoyingjun\else\Test\TestObjectIO.log"); 14 ObjectOutputStream oos = new ObjectOutputStream(fos); 15 oos.writeObject(t); 16 oos.flush(); 17 oos.close(); 18 19 FileInputStream fis = new FileInputStream("D:\zhaoyingjun\else\Test\TestObjectIO.log"); 20 ObjectInputStream ois = new ObjectInputStream(fis); 21 try { 22 T tReaded = (T)ois.readObject(); 23 System.out.println(tReaded.i + " + " + tReaded.j + " + " + tReaded.d + " + " + tReaded.k + " = "); 24 System.out.println(tReaded.i + tReaded.j + tReaded.d + tReaded.k); 25 26 } catch (ClassNotFoundException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } catch (IOException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } 34 } 35 } 36 37 class T implements Serializable 38 { 39 int i = 10; 40 int j = 9; 41 double d = 2.3; 42 int k = 15; 43 }
输出结果:
1 10 + 9 + 2.3 + 8 = 2 29.3
结合transient关键字使用:
1 package com.zyjhandsome.io; 2 3 import java.io.*; 4 5 public class TestObjectIO { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 T t = new T(); 10 t.k = 8; 11 12 try { 13 FileOutputStream fos = new FileOutputStream("D:\zhaoyingjun\else\Test\TestObjectIO.log"); 14 ObjectOutputStream oos = new ObjectOutputStream(fos); 15 oos.writeObject(t); 16 oos.flush(); 17 oos.close(); 18 19 FileInputStream fis = new FileInputStream("D:\zhaoyingjun\else\Test\TestObjectIO.log"); 20 ObjectInputStream ois = new ObjectInputStream(fis); 21 try { 22 T tReaded = (T)ois.readObject(); 23 System.out.println(tReaded.i + " + " + tReaded.j + " + " + tReaded.d + " + " + tReaded.k + " = "); 24 System.out.println(tReaded.i + tReaded.j + tReaded.d + tReaded.k); 25 26 } catch (ClassNotFoundException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } catch (IOException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } 34 } 35 } 36 37 class T implements Serializable 38 { 39 int i = 10; 40 int j = 9; 41 double d = 2.3; 42 transient int k = 15; 43 }
输出结果:
1 10 + 9 + 2.3 + 0 = 2 21.3