我试图在不移动指针的情况下阅读下一行,这可能吗?
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
感谢。
答案 0 :(得分:40)
您可以使用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
答案 1 :(得分:15)
只需读取循环中的当前行和下一行。
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) {}
}