0

I am trying to read an InputStream twice. But when I try to reset the stream and read it says no bytes read. I changed from InputStream to BufferedInputStream still reset doesn't work for me. What could be the mistake that I am doing?

Below is my code:

byte[] buffer = new byte[READ_BUFFER_SIZE];
int bytesRead=0;
        InputStream _baseStream =  new FileInputStream("slot.txt");
        BufferedInputStream buff =new BufferedInputStream(_baseStream);
        try {

            bytesRead = buff.read(buffer, 0, READ_BUFFER_SIZE);
            System.out.println("1. "+bytesRead);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if(bytesRead>0)
        {
            buff.mark(10);
            buff.reset();
            try {
                //bytesRead = _baseStream.read(buffer, 0, READ_BUFFER_SIZE);
                bytesRead = buff.read(buffer, 0, READ_BUFFER_SIZE);
                System.out.println("2. "+bytesRead);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

Output:

  1. 39
  2. -1
Bulat
  • 720
  • 7
  • 15
  • Look up here https://stackoverflow.com/questions/9501237/read-stream-twice?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Wulf Apr 18 '18 at 06:57
  • You have to `mark` *before* you read and `reset` to jump back to the marked position. See the documentation https://docs.oracle.com/javase/8/docs/api/ – mtj Apr 18 '18 at 07:01
  • i changed the buff.mark() to begin of code. and it worked.thanks – user9450093 Apr 18 '18 at 07:52

0 Answers0