操作对象
ObjectInputStream与ObjectOutputStream
就是把对象持久化(对象存储到硬盘上),表现形式就是对象文件
持久化对象必须实现Serializable接口
1 public class Person implements Serializable { 2 private String name; 3 private int age; 4 5 public Person() { 6 super(); 7 } 8 9 public Person(String name, int age) { 10 super(); 11 this.name = name; 12 this.age = age; 13 } 14 15 public String getName() { 16 return name; 17 } 18 19 public void setName(String name) { 20 this.name = name; 21 } 22 23 public int getAge() { 24 return age; 25 } 26 27 public void setAge(int age) { 28 this.age = age; 29 } 30 }
一、ObjectOutputStream
1 public static void writeObj() throws IOException { 2 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.object")); 3 oos.writeObject(new Person("zhang",13)); 4 oos.close(); 5 }
二、ObjectInputStream
1 private static void readObj() throws IOException, ClassNotFoundException { 2 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.object")); 3 Person p=(Person)ois.readObject(); 4 System.out.println(p.getName()+":"+p.getAge()); 5 }
原文地址:https://www.cnblogs.com/WarBlog/p/12141793.html
时间: 2024-11-12 15:27:51