简体   繁体   English

Can BufferedReader(Java)可以在不移动指针的情况下读取下一行吗?

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


I am trying to read next next line without moving the pointer, is that possible? 我试图在不移动指针的情况下阅读下一行,这可能吗?

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

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

the While will read line by line as i want, but i need to write the next line of the current line. 虽然我会想要逐行阅读,但我需要写下当前行的下一行。

it is possible? 有可能的?

my file contain Http request data, the first line is the GET request, 我的文件包含Http请求数据,第一行是GET请求,
in the second line the Host name, i need to pull out the Host before the GET to be able to connect it together. 在第二行主机名,我需要在GET之前拉出主机才能将它们连接在一起。
Host/+the GET url, 主持人/ + GET网址,

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

Thanks. 谢谢。

You can use mark() and reset() to mark a spot in the stream and then return to it. 您可以使用mark()reset()在流中标记一个点,然后返回它。 Example: 例:

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

Just read both current and next line in the loop. 只需读取循环中的当前行和下一行。

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