You can do this two different ways. One is simply to make a new Scanner object, which seems to be what you want. To do that you just assign a new Scanner object to the same variable, and then you can read from the new Scanner. Something like this:
Scanner scan = new Scanner(file);
// Code reading contents of file
scan.close();
scan = new Scanner(file2);
// Code reading contents of file2
scan.close();
Now, you actually asked about using a single Scanner object to read from multiple files, so technically the above code doesn't answer your question. If you look at the documentation for Scanner, there is no method to change input sources. Thankfully, Java has a neat little class called SequenceInputStream. This lets you combine two input streams into one. It reads from the first input stream until it is completely exhausted, and then it switches to the second one. We can use this to read from one file, and then switch to a second file, all in one input stream. Here's an example of how you could do this:
// Create your two separate file input streams:
FileInputStream fis1 = new FileInputStream(file);
FileInputStream fis2 = new FileInputStream(file2);
// We want to be able to see the separation between the two files,
// so I stuck a double line separator in here (not necessary):
ByteArrayInputStream sep = new ByteArrayInputStream((System.lineSeparator() + System.lineSeparator()).getBytes());
// Combine the first file and the separator into one input stream:
SequenceInputStream sis1 = new SequenceInputStream(fis1, sep);
// Combine our combined input stream above and the second file into one input stream:
SequenceInputStream sis2 = new SequenceInputStream(sis1, fis2);
// Print it all out:
try (Scanner scan = new Scanner(sis2)) {
scan.forEachRemaining(System.out::println);
}
This will produce something like:
Content
of
file
1
Content
of
file
2
Now you've truly only created one Scanner object, and you read input from two different files with it.
Note: I have left out all exception handling in the above code snippets to reduce boilerplate code, since the question was not explicitly about exceptions. I assume you know how to handle exceptions on your own.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…