2015-10-01 48 views
1

我使用此代碼片段從網頁中讀取文本並將其保存爲字符串?如何重置BufferedReader(或InputStreamReader)以使用readline()兩次?

我想readline()函數從開始。所以它會再次讀取網頁的內容。我該怎麼做

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 
       } 
+0

@JeanJung - 隨着OP的方式構建'fullText',它沒有任何換行符。 –

回答

2

只能標記爲Reader的位置(並返回到它與reset())如果markSupported回報true,我很懷疑流通過httpURLConnection.getInputStream()返回支持標記。

我認爲最好的選擇是將響應讀入緩衝區,然後在緩衝區中創建儘可能多的讀取器。您將需要包含行終止字符(您當前放棄)以保留行結構。如果你的InputStream實際上 用的markSupported()方法:(或者,您也可以讀取響應爲List<String>,而不是爲單一String

0

InputStream will not reset to beginning

你流的BufferedInputStream對象內像支持使用標記。根據API,InputStream類不會,但是java.io.BufferedInputStream類可以。也許你應該嵌入您的流的BufferedInputStream對象中,如:

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

除'getChannel()'沒有爲'InputStream'定義。 –

+0

你是對的..對不起,這隻適用於FileInputStreams。 –

相關問題