对象序列化与反序列化

    科技2022-08-28  100

    import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Test6 { public static void main(String[] args) throws IOException, ClassNotFoundException { Person1 p1=new Person1("杨勇", 18); ObjectOutputStream ops=new ObjectOutputStream(new FileOutputStream("D:/obj.txt")); //建立Obj字节输出流通道,新建D:/obj.txt文件并将其序列化成字节 ops.writeObject(p1);; //将对象p1保存到ops ops.close(); //关闭流通道 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:/obj.txt")); //建立Obj字节输入流通道,新建D:/obj.txt文件并将其反序列化成对象 Object oh=ois.readObject(); //读取ois中的对象赋值给oh System.out.println(oh); ois.close(); //关闭流通道 } } class Person1 implements Serializable{ String name; int age; @Override public String toString() { return "姓名:" + name + ", 年龄:" + age ; } public Person1(String name, int age) { super(); this.name = name; this.age = age; } }

     

    Processed: 0.010, SQL: 9