简体   繁体   English

重置 ObjectOutPutStream 以更新新的 object state?

[英]Reset ObjectOutPutStream to update new object state?

I want to reset ObjectOutPutStream to update the new object state.我想重置 ObjectOutPutStream 以更新新的 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;
        }
    }
}


在此处输入图像描述

You are writing two copies of an object but only reading one.您正在编写 object 的两份副本,但只读取一份。 If you read two objects you will see BEFORE and AFTER.如果您阅读两个对象,您将看到 BEFORE 和 AFTER。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM