ObjectInutStream ObjectOutputStream 对象序列化原理 --- Serializable

来源:互联网 发布:citra3ds模拟器mac版 编辑:程序博客网 时间:2024/04/19 08:47
 
package namespace;import java.io.*;import java.util.*;class Person implements Serializable{private String name;private int age;public Person(String name,int age){this.name=name;this.age=age;}public String toString(){return name+":"+age;}}public class IOTest {public static void main(String args[]) {try {//writeObj();readObj();//readint();}catch(Exception e){System.out.println("文件读取结束");}}public static void writeObj() throws Exception {ObjectOutputStream objout = new ObjectOutputStream(new FileOutputStream("F:\\person.obj",true));objout.writeObject(new Person("gir",30));objout.writeObject(new Person("person",30));objout.close();}public static void readObj() throws Exception {ObjectInputStream objin = new ObjectInputStream(new FileInputStream("F:\\person.obj"));Person p = null;while((p=(Person)objin.readObject())!=null){System.out.println(p);}objin.close();System.out.println(p);}public static void readint() throws Exception {ObjectInputStream objin = new ObjectInputStream(new FileInputStream("F:\\person.obj"));int data = objin.readInt();objin.close();System.out.println(data);}}/* *  * ObjectInputStream  里面的读取方法在读取一个有类型的数据进,如果一个读取失败将是致命的,整个程序会异常结束 * 而其也没有一个固定的文件结束的返回标志,因此这个要在异常里面进行处理就可以了 *  * 还有文件序列化的时候继承接口 Serializable接口,接口里面有一个finally static long SerialversionUID 来标识对象的唯一性, * 如果在自己的类中定义一个相同的变量来覆盖接口中的,那么即使两个类中的对象不一样,那么序列化的过程中也会把这两个对象认为是同 * 一个对象来处理 *  *2011/11/2  17:19:4  * */

原创粉丝点击