从文件中读取序列化对象?

时间:2014-02-17 22:34:39

标签: java

我想从目标文件中编写和读取可序列化的类。我可以将这个对象写入一个文件,但我似乎无法读回该对象并将其写入控制台。

这些选项中的任何一个都不起作用。我只想读取对象,因为它被写入目标文件。

Code Tried:

public void readBinary1() throws IOException, ClassNotFoundException {
        ObjectInputStream input = new ObjectInputStream(new FileInputStream
                                      ("G:\\testobject.tmp"));
        input.readObject();

        System.out.println(new myClass());
    }

    public void readBinary1() throws IOException, ClassNotFoundException {
        ObjectInputStream input = new ObjectInputStream(new FileInputStream
                                      ("G:\\testobject.tmp"));

        System.out.println(new myClass(input.readObject()));
    }

类:

class myClass implements Serializable {
    myClass() {}

    myClass(myClass b) {
       this.a = b.a;
       this.b = b.b;
    }

    private static final long serialVersionUID = 1L;
    private int a = 0;
    private int b = 100;
    private transient int c = 50;
}

已添加代码:

    I had to add a toString to my class to do it the way that it was suggested to do. That seems to be the way that is easiest in the short run but I would rather write the object and then be able to read in the object with out having to use the toString. Is there a way that I can read in the object with one read and then be able to break the info apart with the .dot notation. Such as mc.variable1 and mc.variable2 and so on. I had to type cast the read object also before the code would compile.

有几个输入和输出流允许将对象序列化为文件。我确信有不同的方法来包装读取的类,并且想知道哪种方式是创建读取的最佳方式。

1 个答案:

答案 0 :(得分:1)

这样做:

myClass readedObject = (myClass) input.readObject();
System.out.println(readedObject);