This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes Mark the current position in Output Stream Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Mark the current position in Output Stream" Watch "Mark the current position in Output Stream" New topic

Mark the current position in Output Stream

Maheshwari Anuj

Joined: May 03, 2010
Posts: 14

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?

Rob Spoor

Joined: Oct 27, 2005
Posts: 20078

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.

How To Ask Questions How To Answer Questions
subject: Mark the current position in Output Stream
It's not a secret anymore!