1

BufferedReader object that has data from socket. How to get whole BufferedReader content without erasing it. I need it for tracing purposes.

vico
  • 17,051
  • 45
  • 159
  • 315

1 Answers1

1

You should mark() the starting buffer position, so that your reset() call comes back to the beginning. For example, if you are reading chars, and want to mark a position to come back:

Data sample: A B C D

System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.mark(4); // save the position
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.reset() // back to 4
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());

Will print:

A B C D C D

(as a char takes 2 bytes)

aran
  • 10,978
  • 5
  • 39
  • 69
  • 1
    Won't using `mark` for this use case require the `BufferedReader` to allocate a buffer large enough to hold the entire stream? From the `readAheadLimit` parameter documentation: "_Limit on the number of characters that may be read while still preserving the mark. An attempt to reset the stream after reading characters up to this limit or beyond may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care_". – Slaw May 31 '19 at 11:30
  • Yep, but I don't see any problems with that. If he reads the stream of the bufferedreader until the end, and each time that end is reached, it resets the position and save its contents (somehow), then this logic could be valid as well for BufferedReaders that must be resetted (emptied and filled, such as reading a 10000 pages log), since you are "rolling back" each "stream-piece", everytime. – aran May 31 '19 at 11:38
  • Hmm, not sure I understand your comment. As I understand the documentation, if the input is gigabytes in size it will need to allocate a gigabytes sized buffer in order to support resetting back to the start after reading to the end (which I believe is what the OP wants to do). On top of that, the OP will possibly need to know ahead of time a good value for `readAheadLimit`, lest it's too small or unnecessarily large (and thus cause the allocation of an unnecessarily large buffer). – Slaw May 31 '19 at 11:46
  • 1
    If there's an input of 1 GB that he must roll back and get as a piece, then yes... for sure he will need to allocate a 1GB of "full" - buffer somewhere : ). What I meant is, the same thing you do in pieces with the bufferedReader, can be done to save its contents: If the buffer is filled and emptied 10 times during a 1GB read (100MB chunks), then he could use this same logic, and save the contents 10 times, elsewhere (compressed, maybe?), each time the buffer is filled with 100mb. But, if he wants to save the content of 1 GB inside ONE buffer, then, that's another problem I can't solve! : ) – aran May 31 '19 at 11:49