Reading a text file using BufferedReader and Scanner

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?

Upvotes: 3

Views: 6241

Answers (1)

aioobe
aioobe

Reputation: 421290

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

Upvotes: 7

Related Questions