1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.io.*; public class User implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } public static void main(String[] args) throws IOException, ClassNotFoundException { // User user = new User("gol",22); // ByteArrayOutputStream bo = new ByteArrayOutputStream(); // ObjectOutputStream oo = new ObjectOutputStream(bo); // oo.writeObject(user);//序列化.user写入字节数组流中 // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); // ObjectInputStream oi = new ObjectInputStream(bi); // User userSer = (User) oi.readObject();//反序列化 // System.out.println(userSer); User user = new User("gol",22); FileOutputStream fos = new FileOutputStream("a.txt"); ObjectOutputStream oo = new ObjectOutputStream(fos); oo.writeObject(user);//序列化.user写入文件中 FileInputStream fis = new FileInputStream("a.txt"); ObjectInputStream oi = new ObjectInputStream(fis); User userSer = (User) oi.readObject();//反序列化 System.out.println(userSer); oi.close(); fis.close(); oo.close(); fos.close(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import java.io.*; public class User implements Externalizable { private static final long serialVersionUID = 1L; private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.name);//将属性分别序列化 out.writeObject(this.age); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.name=(String)in.readObject();//反序列化属性 this.age=(int)in.readObject(); } public static void main(String[] args) throws IOException, ClassNotFoundException { FileOutputStream fos = new FileOutputStream("a.txt"); ObjectOutputStream oo = new ObjectOutputStream(fos); FileInputStream fis = new FileInputStream("a.txt"); ObjectInputStream oi = new ObjectInputStream(fis); User user = new User("gol",19); user.writeExternal(oo);//序列化 User userEnr = new User(); userEnr.readExternal(oi);//反序列化 System.out.println(userEnr); oi.close(); fis.close(); oo.close(); fos.close(); } } |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |