This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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
Author

Mark the current position in Output Stream

Maheshwari Anuj
Greenhorn

Joined: May 03, 2010
Posts: 14
Hi,

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?

Regards,
Anuj
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mark the current position in Output Stream
 
Similar Threads
java.io.IOException: mark/reset not supported --WHATS THAT???? need u experts help
Runtime getRuntime() exec(String command) - How does this work?
Java I/O for two file
randomly reading from the stream ??
Ranchers,Clarification on UTF-8 in Java