This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have a requirement in which I have to go back in the Output Stream to a particular position and then write some data there. Input Stream have mark() and reset() methods but I did't find anything like this in Output Stream. Can anyone help?
There isn't anything like that in the API. However, you can always write it yourself. Here is one approach
- extend FilterOutputStream; that way your class will act as a wrapper around any other OutputStream.
- keep a buffer of bytes written to your stream but not to the wrapped OutputStream.
- when calling flush() you clear the buffer and write its contents to the wrapped OutputStream.
- when setting the "savepoint" you first flush() your OutputStream so the buffer is cleared.
- when resetting to the savepoint you simply clear the buffer
You can perhaps optimize the code by only using the buffer if you have a savepoint set. flush() removes the savepoint. I'd use a ByteArrayOutputStream or a List<Byte> for the buffer.