Reading a text file using BufferedReader and Scanner

雨燕双飞 提交于 2019-12-10 19:04:39

问题


I need to read the first n lines of a text file as lines (each line may or may not contain whitespace). The remainder of the text file contains an unknown number N of tokens that are whitespace-delimited (delimiters are a mixture of space, tab, and newline characters, all to be treated identically as delimiters).

I know how to read lines using BufferedReader. I know how to read tokens using Scanner. But how do I combine these two different modes of reading for a single text file, in the above described manner?


回答1:


You could use a Scanner for both tasks. See the Scanner.nextLine method.

If you really need to use both a BufferedReader and a Scanner you could simply do it like this:

byte[] inputBytes = "line 1\nline 2\nline 3\ntok 1 tok 2".getBytes();
Reader r = new InputStreamReader(new ByteArrayInputStream(inputBytes));

BufferedReader br = new BufferedReader(r);
Scanner s = new Scanner(br);

System.out.println("First line:  " + br.readLine());
System.out.println("Second line: " + br.readLine());
System.out.println("Third line:  " + br.readLine());

System.out.println("Remaining tokens:");
while (s.hasNext())
    System.out.println(s.next());

Output:

First line:  line 1    // from BufferedReader
Second line: line 2    // from BufferedReader
Third line:  line 3    // from BufferedReader
Remaining tokens:
tok                    // from Scanner
1                      // from Scanner
tok                    // from Scanner
2                      // from Scanner


来源:https://stackoverflow.com/questions/7635917/reading-a-text-file-using-bufferedreader-and-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!