Object to String.
I want somehow to save object to string and later restore it.
I have class MyClass. I want to create object, work with it and then save object properties to string. Later to start program and init object from that string.
I see that there is toString() method. But i am not sure it do that i need.
The class i code will be extended and i don't know now what properties will final class have.
How to save the object to string?
Did you read that what toString() method is doing?
Can you show what you have done so far.
You can use the built-in java serialization. Or serialize java objects to XML. Do a google search "Java Serialization" to find out more.
You want to save the contents of an instance of your class in a disk file so that you can later read that file and recreate the object.
One way is to use serialization, another is to convert all the class's variables contents to a String and then write it a file. To get the object back, have a constructor in that class that will take the String that was written to the file and create an instance of the class.
Yes. I think something like serialization.
I have found some examples but there object is saved to file. I don't want to save object to file. I want to save it to string.
Can you write example where object it serialised and saved to string variable not in file?
Hmm. And then how do you save the String?
I have found the way to do this.
That is not readable string. But i must convert that bytes to string becouse it is the only way to transfer the object to externall app and the get it back.
and sobj contains data that then can be read back to object
MyClass a=new MyClass();
ByteArrayOutputStream fos = new ByteArrayOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream( fos );
outStream.writeObject( a );
This works as i expected.
MyClass b=new MyClass();
ByteArrayInputStream input = new ByteArrayInputStream(sobj.getBytes());
ObjectInput oi = new ObjectInputStream(input);
b = (MyClass)oi.readObject();