I want to write objects in human readable form in a text file, the file gets saved as a normal serialized object with unwanted characters instead.
How do I rewrite t
It really depends on what you need the file to do. If you don't want to use the objects' toString()
representations, you need to extract the content of each object, and come up with a delimiter, and use that delimiter to separate your data (book
(s)). Note, you'd need a different delimiter to separate the data in each object. You can standardize how you write to the file, so that individual elements are easily retrieved. If you can come up with a delimiter, you can read in the data for one book
as a String
and use split()
to put each attribute into an array slot. If this is just for people to read, you can do something similar, but formatted nicely, so people know what they're actually reading. The object's toString()
may be good for that:
For reference, here's a toString()
for your object:
public String toString()
{
return name + " " + author + " " + price;
}
That was just an example, but if you put that in your book class and then attempt to print a book object, you'll get its name author price
as the printout.
Also, you should use constructors/methods to assign values to your object's instance members, which should be private
.
Ideally, I think you should use xml for your serialization; see XStream.