序列化 小复习
想要序列化一個(gè)對(duì)象則需要使其繼承serializable或者externalizable接口
一下是一個(gè)實(shí)例小程序:
ser_test 1 import java.io.*; 2 3 public class ser_test{ 4 public static void main(String[] args) throws Exception{ 5 person p1 = new person(1,1.2,"A"); 6 FileOutputStream fos = new FileOutputStream("/person.txt"); 7 ObjectOutputStream oos = new ObjectOutputStream(fos); 8 oos.writeObject(p1); 9 oos.close(); 10 fos.close(); 11 System.out.println("output over!"); 12 } 13 } 14 15 class person implements Serializable{ 16 int age; 17 double height; 18 String name; 19 person(){} 20 person(int age,double height,String name){ 21 this.age = age; 22 this.height = height; 23 this.name = name; 24 } 25 }實(shí)驗(yàn)結(jié)果:
在根目錄下的person.txt文件中有如下內(nèi)容
輸出流把person對(duì)象的內(nèi)容以二進(jìn)制形式寫到txt中,所以是亂碼,但是還是能從中看到一些person的痕跡。
接下來
在以上內(nèi)容中增加輸入流把文件中的內(nèi)容讀取出來并在控制臺(tái)顯示
View Code 1 import java.io.*; 2 3 public class ser_test{ 4 public static void main(String[] args) throws Exception{ 5 person p1 = new person(1,1.2,"A"); 6 FileOutputStream fos = new FileOutputStream("/person.txt"); 7 ObjectOutputStream oos = new ObjectOutputStream(fos); 8 oos.writeObject(p1); 9 oos.close(); 10 fos.close(); 11 System.out.println("output over!"); 12 13 14 FileInputStream fis = new FileInputStream("/person.txt"); 15 ObjectInputStream ois = new ObjectInputStream(fis); 16 person p2 = (person)ois.readObject(); 17 System.out.println("person = " + "age :" + p2.age + " height :" + p2.height + " name : " + p2.name); 18 System.out.println("output over!"); 19 } 20 } 21 22 class person implements Serializable{ 23 int age; 24 double height; 25 String name; 26 person(){} 27 person(int age,double height,String name){ 28 this.age = age; 29 this.height = height; 30 this.name = name; 31 } 32 }結(jié)果:
讀取完畢!
在序列化是需要注意的是如果對(duì)象中的變量有static 或者transient修飾的話序列化時(shí)這部分不能序列化。
將上面程序中的person類稍作修改:
1 class person implements Serializable{ 2 static int age; 3 transient double height; 4 String name; 5 person(){} 6 person(int age,double height,String name){ 7 this.age = age; 8 this.height = height; 9 this.name = name; 10 } 11 }?
結(jié)果:
從文本中內(nèi)容可以看出age和height沒有寫入
externalizable接口是自己定序列化規(guī)則,小菜暫時(shí)沒涉及到這么深的應(yīng)用,如果有機(jī)會(huì)以后在補(bǔ)充
轉(zhuǎn)載于:https://www.cnblogs.com/zhuojiniao/archive/2013/04/21/3033901.html
總結(jié)
- 上一篇: oracle t7-2报价,Sun/Or
- 下一篇: LitePal简单用法