有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

这两种选择都不起作用。我只想在写入对象文件时读入对象

已尝试的代码:

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) 个答案

  1. # 1 楼答案

    这样做:

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