簡體   English   中英

Can BufferedReader(Java)可以在不移動指針的情況下讀取下一行嗎?

[英]Can BufferedReader (Java) read next line without moving the pointer?


我試圖在不移動指針的情況下閱讀下一行,這可能嗎?

BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));

while ((readString = buf.readLine()) != null) {
}

雖然我會想要逐行閱讀,但我需要寫下當前行的下一行。

有可能的?

我的文件包含Http請求數據,第一行是GET請求,
在第二行主機名,我需要在GET之前拉出主機才能將它們連接在一起。
主持人/ + GET網址,

GET /logos/2011/family10-hp.jpg HTTP/1.1  
Host: www.google.com  
Accept-Encoding: gzip  

謝謝。

您可以使用mark()reset()在流中標記一個點,然后返回它。 例:

int BUFFER_SIZE = 1000;

buf.mark(BUFFER_SIZE);
buf.readLine();  // returns the GET
buf.readLine();  // returns the Host header
buf.reset();     // rewinds the stream back to the mark
buf.readLine();  // returns the GET again

只需讀取循環中的當前行和下一行。

BufferedReader reader = null;
try {
    reader = new BufferedReader(new InputStreamReader(file, encoding));
    for (String next, line = reader.readLine(); line != null; line = next) {
        next = reader.readLine();

        System.out.println("Current line: " + line);
        System.out.println("Next line: " + next);
    }
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM