Я хочу написать и прочитать сериализуемый класс из объектного файла. Я могу записать этот объект в файл, но, похоже, я не могу прочитать объект обратно и записать его на консоль.Чтение сериализованного объекта из файла?
Ни один из этих вариантов не работает. Я просто хочу прочитать в объекте, как он был записан в объектный файл.
Код Пробовал:
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.
Есть несколько входных и выходных потоков, которые позволяют сериализации объектов в файл. Я уверен, что есть разные способы обертывания классов для чтения и интересно также, каким способом был лучший способ создать чтение.
Попробуйте найти эту проблему на переполнение стека - есть буквально десятки подобных вопросов и ответов. –
см. Http://stackoverflow.com/questions/17293991/how-to-write-and-read-java-serialized-objects-into-a-file – michael
Вы, кажется, не понимаете, что читаете * сериализованный объект * из потока. 'MyClass mc = (MyClass) input.readObject();'. Готово. –