How do I reset a scanner to the beginning of a file? If this is not possible can I make a copy of a scanner?
Printable View
How do I reset a scanner to the beginning of a file? If this is not possible can I make a copy of a scanner?
I think that you will need to create a new Scanner object.
I agree completely.
@OP - this is probably worth ignoring
But, strangely, the following does ... something
Code:import java.io.IOException;
import java.io.StringReader;
import java.util.Scanner;
public class ScannerEg {
public static void main(String[] args) throws IOException {
String data = "This is a\nthree line\nimitation file";
StringReader in = new StringReader(data);
Scanner scanner = new Scanner(in);
int counter = 1;
//while(scanner.hasNext()) {
// System.out.printf("%d: %s%n", counter++, scanner.next());
//}
//System.out.printf("%d: %s%n", counter++, scanner.next());
scanner.next();
in.reset();
while(scanner.hasNext()) {
System.out.printf("%d: %s%n", counter++, scanner.next());
}
}
}
I think the scanner "reads ahead", so resetting the underlying stream will not do what you expect. It's no good skip()ping the unwanted input because once the scanner has seen the end of the stream hasNext() returns false even after the stream has been reset.
StreamTokenizer, however, is a well behaved "wrapper" that respects the capacities of the underlying stream.