Java 如何将BufferedReader(或InputStreamReader)重置为使用readline()两次?
我使用此代码段从网页a读取文本并将其保存为字符串 我希望readline()函数从最前面开始。所以它会再次阅读网页的内容。我该怎么做Java 如何将BufferedReader(或InputStreamReader)重置为使用readline()两次?,java,android,stream,Java,Android,Stream,我使用此代码段从网页a读取文本并将其保存为字符串 我希望readline()函数从最前面开始。所以它会再次阅读网页的内容。我该怎么做 if (response == httpURLConnection.HTTP_OK) { in = httpURLConnection.getInputStream(); isr = new InputStreamReader(in); br = new Buffer
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
}
如果
markSupported
返回true
,则只能标记读取器的位置(并使用reset()
返回该位置),并且我非常怀疑httpURLConnection.getInputStream()
返回的流是否支持标记
我认为,最好的选择是将响应读入缓冲区,然后您可以在该缓冲区上创建任意数量的读取器。您需要包含行终止字符(当前正在丢弃)以保留行结构。(或者,您可以将响应读入列表中,而不是读入单个字符串中)
BufferedInputStream对象中的流,如:
如果您的InputStream实际上支持使用mark,则使用markSupported()方法。根据API,InputStream类没有,但是java.io.BufferedInputStream类有。也许您应该将流嵌入BufferedInputStream对象中,如:
@JeanJung-按照OP构造全文
的方式,它没有任何换行字符。除了getChannel()
没有为InputStream
定义之外。你是对的。。抱歉,这仅适用于FileInputStreams。
InputStream data = new BufferedInputStream(realResponse.getEntity().getContent());
// data.markSupported() should return "true" now
data.mark(some_size);
// work with "data" now
...
data.reset();