开发者

working of ObjectInputStream

I've got multiple objects stored in a file .This is regarding the ObjectInputStream. If I've got the below code:

FileInputStream fis = new FileInputStream(filename);

ObjectInputStream ois = new ObjectInputStream(fis);

Object obj1 = (Object)ois.readObject();

ois.close();
 ois = new ObjectInputStream(fis);

Object obj2 = (Object)ois.readObject();

My question is : will the readObject called from the second Object stream (obj2) be the 1st or 2nd obj开发者_运维问答ect in the file


It will infact throw an exception. Calling close on the ObjectInputStream will close the FileInputStream as well.


It depends on how you stored the objects. If you used one single ObjectOutputStream, then you better also use one single ObjectInputStream.

If you used separate streams for the output, you also should use separate streams for the input. But this is not really recommended.


For your "persistent queue", I would recommend something like this:

On the sending side:

  • Create a ByteArrayOutputStream, wrap an ObjectOutputStream around it.
  • Write the object to the OOS, and close the OOS.
  • Get the byte[], and write it together with a header indicating the length to your queue-stream.

On the receiving side:

  • read a header length from the queue stream.
  • read a byte[] of the given length from the queue stream.
  • create an ByteArrayInputStream from this array, and wrap an ObjectInputStream around it.
  • read one object from the OIS, close the OIS.

When you store parts of your queue, make sure to always store whole messages (i.e. the header together with the object).

Of course, it might be easier to use already existing solutions, like JMS (where you would create an ObjectMessage, and submit it to the queue).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜