简体   繁体   English

如何重置BufferedReader(或InputStreamReader)以两次使用readline()?

[英]How to reset BufferedReader (or InputStreamReader) to use readline() twice?

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. 我希望readline()函数从一开始就开始。 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
                }

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. 如果markSupported返回true ,则只能标记Reader的位置(并通过reset()返回),并且我非常怀疑httpURLConnection.getInputStream()返回的流httpURLConnection.getInputStream()支持标记。

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 .) (或者,您可以将响应读取到List<String>而不是单个String 。)

From InputStream will not reset to beginning InputStream不会重置为开始

your stream inside a BufferedInputStream object like: with the markSupported() method if your InputStream actually support using mark. 如果您的InputStream实际上支持使用mark,则使用markSupported()方法在BufferedInputStream对象(如:)中存储您的流。 According to the API the InputStream class doesn't, but the java.io.BufferedInputStream class does. 根据API,InputStream类没有,但java.io.BufferedInputStream类却有。 Maybe you should embed your stream inside a BufferedInputStream object like: 也许您应该将流嵌入到BufferedInputStream对象中,例如:

InputStream data = new BufferedInputStream(realResponse.getEntity().getContent());
// data.markSupported() should return "true" now
data.mark(some_size);
// work with "data" now
...
data.reset();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM