想要序列化一个对象则需要使其继承serializable或者externalizable接口
一下是一个实例小程序:
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 }
实验结果:
在根目录下的person.txt文件中有如下内容
输出流把person对象的内容以二进制形式写到txt中,所以是乱码,但是还是能从中看到一些person的痕迹。
接下来
在以上内容中增加输入流把文件中的内容读取出来并在控制台显示
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 }
结果:
读取完毕!
在序列化是需要注意的是如果对象中的变量有static 或者transient修饰的话序列化时这部分不能序列化。
将上面程序中的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 }
结果:
从文本中内容可以看出age和height没有写入
externalizable接口是自己定序列化规则,小菜暂时没涉及到这么深的应用,如果有机会以后在补充