1

I use this code snippet to read text from a webpage aand save it to a string?

I would like the readline() function to start from the beggining. So it would read content of the webpage again. How Can I do that

if (response == httpURLConnection.HTTP_OK) {

                in = httpURLConnection.getInputStream();
                isr = new InputStreamReader(in);
                br = new BufferedReader(isr);

                while ((line = br.readLine()) != null) {
                    fullText += line;

                }

                // I want to go through a webpage source again, but
                // I can't because br.readLine() = null. How can I                   put 
                // put a marker on the beginning of the page? 
                while ((line1 = br.readLine()) != null) {
                    fullText1 += line1;
                // It will not go into this loop
                }
user101
  • 595
  • 1
  • 4
  • 18

2 Answers2

2

You can only mark a position for a Reader (and return to it with reset()) if markSupported returns true, and I very much doubt that the stream returned by httpURLConnection.getInputStream() supports marks.

The best option, I think, is to read the response into a buffer and then you can create as many readers as you like over that buffer. You will need to include the line termination characters (which you are currently discarding) to preserve the line structure. (Alternatively, you can read the response into a List<String> rather than into a single String.)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

From InputStream will not reset to beginning

your stream inside a BufferedInputStream object like: with the markSupported() method if your InputStream actually support using mark. According to the API the InputStream class doesn't, but the java.io.BufferedInputStream class does. Maybe you should embed your stream inside a BufferedInputStream object like:

InputStream data = new BufferedInputStream(realResponse.getEntity().getContent());
// data.markSupported() should return "true" now
data.mark(some_size);
// work with "data" now
...
data.reset();
Community
  • 1
  • 1
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62