开发者

Reset ObjectOutPutStream to update new object state?

开发者 https://www.devze.com 2023-03-10 17:34 出处:网络
I want to reset ObjectOutPutStream to update the new object state. But why it doesn\'t effect. The below code outputs \"BEFORE\" instead of \"AFTER\"? What\'s wrong with my code?

I want to reset ObjectOutPutStream to update the new object state. But why it doesn't effect. The below code outputs "BEFORE" instead of "AFTER"? What's wrong with my code?


package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serialization {
    public static void main(String[] strs) {
        String filename = "E:\\myObject.data";

        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        MyObject myObject = new MyObject();
        try {

            myObject.setValue("BEFORE");
            fos = new FileOutputStream(filename);
            out = new ObjectOutputStream(fos);
            out.writeObject(myObject);
            out.reset();
            myObject.setValue("AFTER");
            out.writeObject(myObject);
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            FileInputStream fis = null;
            ObjectInputStream in = null;
            fis = new FileInputStream(filename);
            in = new ObjectInputStream(fis);
            myObject = (MyObject) in.readObject();
            System.out.println(myObject.getValue());
            in.close();
        } catch (IOException ex) 开发者_运维问答{
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    public static class MyObject implements Serializable {

        private static final long serialVersionUID = 5222199410120362372L;
        private String value;

        public void setValue(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }
}


Reset ObjectOutPutStream to update new object state?


You are writing two copies of an object but only reading one. If you read two objects you will see BEFORE and AFTER.

0

精彩评论

暂无评论...
验证码 换一张
取 消