【发布时间】:2014-02-17 22:34:39
【问题描述】:
我想从一个目标文件中写入和读取一个可序列化的类。我可以将此对象写入文件,但我似乎无法重新读取该对象并将其写入控制台。
这些选项都不起作用。我只想在对象被写入对象文件时读取它。
代码尝试:
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.
有几个输入和输出流允许将对象序列化为文件。我确信有不同的方式来包装读取的类,并且想知道哪种方式是创建读取的最佳方式。
【问题讨论】:
-
尝试在堆栈溢出上搜索这个问题——实际上有几十个类似的问题和答案。
-
您似乎不明白您正在从流中读取序列化对象。
MyClass mc = (MyClass) input.readObject();。完成。 -
我知道我正在读取一个序列化对象。我认为它将整个对象读入变量,然后我必须将这些信息分解成我想要用它做的事情,比如写或打印或其他什么。如果我从文件中读取一个对象,它应该一次将其全部读取,就像我从文件中读取一个字符串一样。它会一次读取一个字符串。
标签: java