Person
1 package MyTest; 2 3 import java.io.Serializable; 4 5 public class Person implements Serializable { 6 /** 7 * 8 */ 9 private static final long serialVersionUID = 1L; 10 private String name; 11 private int age; 12 13 public Person(String name, int age) { 14 super(); 15 this.name = name; 16 this.age = age; 17 } 18 19 @Override 20 public String toString() { 21 return name + "\t" + age; 22 } 23 }
FileOutputStream
1 package MyTest; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.ObjectOutputStream; 6 7 8 public class Out { 9 public static void main(String[] args) throws Exception{ 10 File file = new File("1.txt"); 11 FileOutputStream fos = new FileOutputStream(file,true); 12 ObjectOutputStream oos = new ObjectOutputStream(fos); 13 oos.writeObject(new Person("qwe",18)); 14 oos.writeObject(new Person("abc",20)); 15 oos.close(); 16 } 17 }
ObjectInputStream
1 package MyTest; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.ObjectInputStream; 6 7 public class In { 8 public static void main(String[] args) throws Exception { 9 File file = new File("1.txt"); 10 FileInputStream fis = new FileInputStream(file); 11 ObjectInputStream ois = new ObjectInputStream(fis); 12 while(fis.available()>0) { 13 System.out.println(ois.readObject()); 14 } 15 ois.close(); 16 } 17 }
没有true追加进txt信息之前