关闭OutputStream后获取StreamCorruptedException

时间:2014-04-01 20:17:55

标签: java

请帮助,我在我的应用程序中收到StreamCorruptedException。出于某些实施原因,我不得不关闭该流。 这是一个类似于原始应用程序的小代码 读取第三个Dummy对象导致异常。我认为这是因为我在写第三个对象之前关闭了流。我能做什么?

class Dummy implements Serializable{
    int a;
    String b;
    public Dummy(int a, String b) {
        this.a = a;
        this.b = b;
    }
    void Print(){
        System.out.println(a+" "+b);
    }
}
public class Tester {
    public static void main(String []args){
        try {
            ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("test.txt")));
            Dummy a=new Dummy (10,"mm.");
            Dummy b=new Dummy (20,"nn.");
            Dummy c=new Dummy (30,"pp.");
            out.writeObject(a);
            out.writeObject(b);
            out.close();
            out=new ObjectOutputStream(new FileOutputStream(new File("test.txt"),true));
            out.writeObject(c);
            out.close();
            ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("test.txt")));
            Vector<Object> v=new Vector<Object>();
            v.add(in.readObject());
            v.add(in.readObject());
            v.add(in.readObject());
            ((Dummy)v.get(0)).Print();
            ((Dummy)v.get(1)).Print();
            ((Dummy)v.get(2)).Print();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

0 个答案:

没有答案