I want to write and read a serializable class from a object file. I can write this object to a file but I cannot seem to be able to read the object back in and write it to the console.
Neither one of these options works. I just want to read in the object as it was written to the object file.
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:
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;
}
Code Added:
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.
There are couple of input and output streams that allow for the serialization of objects to a file. I am certain that there are different ways to wrap the classes for the read and was wondering also which way was the best way to create the read.