Hello i would like to know if it is possible to work with objectInputStream and ObjectOutputStream without having to load and save to a file. I dont want to depend on any file at the moment, but i would like to work with a stream of object. For exemple a cat instance that i would like to serialize and reconstruct for testing without writing it to a file. Thank you for helping.
Hello and thank your for your answer. How would i transform then my object and pass it to the ByteArrayInputStream ? The constructor takes an array of bytes. How would i transform my object in a byte array ? Thank you.
You create a ByteArrayOutputStream (BAOS), wrap it in an ObjectOutputStream (OOS), write to that OOS and when you're done you retrieve the byte array from the BAOS using the toByteArray() method.
You can then later create a ByteArrayInputStream (BAIS) using that byte array, wrap it in an ObhjectInputStream (OIS) and read from that OIS.
If you want to read before you're done writing, either use multiple BAOS and BAIS instances, or create some other way of redirecting an output stream to an input stream. Perhaps the PipedOutputStream and PipedInputStream classes can help you. Check out their APIs for more info.
Joined: Aug 11, 2007
Hello, So here is what i did and it works for one instance of my class :
But now if i want to test with 2 or more instance of Database, how would i go for it ? The thing is that i want to serialize Database object each time one is created. Is it possible to serialise it in the same file ? Or if i have multiple file (one for each serialized Database) how could i read them all ? Hope i m clear. Thank you for any help on how to go for this kind of work.
If your ObjectOutputStream is writing to the same file then you must not instantiate the ObjectOutputStream multiple times. Each time a new ObjectOutputStream writes to a file it writes a few headers. If you use multiple ObjectOutputStream to write to the same file, these headers will be written multiple times and hence the file will be corrupted. So, if you are using the same file, then share the ObjectOutputStream also.