Java中的IO流 ObjectInputStream和ObjectOutputStream

 

ObjectOutputStream写入对象,可以将多个对象放到集合中,一次性将多个对象写入到文件中。对象要实现序列化Serializable

对象流在写入文件时,类重写加载后写入的内容会覆盖之前的内容,所以要先读取原文本的内容并获取之后再继续添加内容

 1 package object.io;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.ObjectInputStream;
 6 import java.io.ObjectOutputStream;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 public class ObjectStream {
11     public static void main(String[] args) throws Exception {
12         Person p1=new Person("ZTT", 23);
13         Person p2=new Person("ZN", 25);
14         
15         List<Person> persons=new ArrayList<Person>();
16         persons.add(p1);
17         persons.add(p2);
18         FileOutputStream out=new FileOutputStream("D:\\Program Files (x86)\\io\\ObjectStream.txt");
19         ObjectOutputStream oop=new ObjectOutputStream(out);
20         oop.writeObject(persons);
21         
22         oop.close();
23         FileInputStream in=new FileInputStream("D:\\Program Files (x86)\\io\\ObjectStream.txt");
24         ObjectInputStream oip=new ObjectInputStream(in);
25         //oip.read();
26         System.out.println(oip.readObject());
27         oip.close();
28         in.close();
29         
30     }
31 }

 

对象实现序列化Serializable

 1 package object.io;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Person implements Serializable{
 6     @Override
 7     public String toString() {
 8         return "Person [name=" + name + ", age=" + age + "]";
 9     }
10     public String getName() {
11         return name;
12     }
13     public void setName(String name) {
14         this.name = name;
15     }
16     public int getAge() {
17         return age;
18     }
19     public void setAge(int age) {
20         this.age = age;
21     }
22     private String name;
23     private int age;
24     public Person(String name, int age) {
25         super();
26         this.name = name;
27         this.age = age;
28     }
29     public Person() {
30         super();
31     }
32     
33 }

 

posted @ 2017-12-27 09:14  ztt_tttt  阅读(235)  评论(0编辑  收藏  举报