处理流之Object流
•直接把对象写入或读出;
•需要实现serializable接口;
•注意serializable接口中没有定义任何方法,这种接口被称为标记型接口,标记之后给编译器看;(只能保存非静态的成员变量)
•Transient 关键字修饰的成员变量在序列化时不予考虑;
1 package io; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.ObjectInputStream; 9 import java.io.ObjectOutputStream; 10 import java.io.Serializable; 11 12 public class ObjectTest { 13 14 //直接将对象写入和读出 15 public static void main(String[] args) { 16 17 Dog dog = new Dog(); 18 dog.legnumber = 9; 19 20 FileOutputStream fos = null; 21 ObjectOutputStream oos = null; 22 23 FileInputStream fis = null; 24 ObjectInputStream ois = null; 25 26 try { 27 fos = new FileOutputStream(new File("D:/Java_test_file/test/aaa.txt")); 28 oos = new ObjectOutputStream(fos); 29 oos.writeObject(dog); 30 31 fis = new FileInputStream("D:/Java_test_file/test/aaa.txt"); 32 ois = new ObjectInputStream(fis); 33 Dog d = (Dog) ois.readObject(); 34 System.out.println(d.age+" "+d.color+" "+d.legnumber+" "+d.sex); 35 } catch (FileNotFoundException e) { 36 e.printStackTrace(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } catch (ClassNotFoundException e) { 40 41 e.printStackTrace(); 42 } 43 } 44 45 46 47 } 48 49 50 class Dog implements Serializable { 51 52 53 private static final long serialVersionUID = 1L; 54 int age = 10; 55 char sex = '母'; 56 //transient int legnumber = 4; //该属性透明化 透明化后该序列化不考虑该属性值 57 int legnumber = 4; 58 String color = "red"; 59 60 61 }
春风如贵客,一到便繁华