Thought reset() would allow the scanner to start reading the file again from start.
No. It resets state like the what counts as delimiter between the ints (which you are not using). But it doesn't affect the position of the scanner within the stream. So if you reset() then keep reading you will be reading from where you left off (-1 or end of file) not from the start of the file.
By far the easiest way to start reading the file again is to create a new Scanner.
The use of the name "reset" for this functionality could be a little bit confusing because if you reset() a BufferedReader it really does go back to the start. This means that you *can* reuse a Scanner instance if you really, really want to. But, I repeat, it is much easier not to.
To illustrate this I put a file containing "1 2 3 4 5 5 4 3 2 -1 1" in c:\temp\temp.txt and ran the following code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) throws IOException {
test1();
test2();
}
static void test1() throws FileNotFoundException {
Scanner in = new Scanner(new File("c:/temp/temp.txt"));
int count = 0;
while(in.hasNextInt() && in.nextInt() != -1) {
count++;
}
System.out.println(count + " ints found");
in.reset();
System.out.println(in.nextLine());
in.close();
}
static void test2() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("c:/temp/temp.txt"));
br.mark(100000); // <-- mark the start of the underlying reader
Scanner in = new Scanner(br);
int count = 0;
while(in.hasNextInt() && in.nextInt() != -1) {
count++;
}
System.out.println(count + " ints found");
br.reset(); // <-- reset the underlying reader, not the scanner
System.out.println(in.nextLine());
in.close();
}
}
The output is
9 ints found
1
9 ints found
11 2 3 4 5 5 4 3 2 -1 1
The first two lines output show how resetting the Scanner had no effect on its position. The second two show that calling reset() on the underlying BufferedReader allowed content from the beginning to be read again. (although you get a junk character already buffered by the reader).
I don't need the scanner visible outside the try block
My mistake, I see that now the code is formatted.