您可以使用一个扫描仪对象读取多个文件吗?

Can you use one scanner object to read more than one file?

我想知道我是否可以创建一个 Scanner 对象并使用它来读取一个文件,完成读取其内容,然后再读取另一个。

所以不要这样做:

Scanner scan = new Scanner(file);
Scanner scan2 = new Scanner(file2);

我会喜欢

Scanner scan = new Scanner(file);
*Code reading contents of file*
scan = Scanner(file2);

提前致谢!

您可以通过两种不同的方式执行此操作。一种是简单地创建一个新的 Scanner 对象,这似乎是您想要的。为此,您只需将一个新的 Scanner 对象分配给同一个变量,然后您就可以从新的 Scanner 中读取。像这样:

Scanner scan = new Scanner(file);
// Code reading contents of file
scan.close();
scan = new Scanner(file2);
// Code reading contents of file2
scan.close();

现在,您实际上询问了有关使用单个 Scanner 对象读取多个文件的问题,因此从技术上讲,上述代码无法回答您的问题。如果你看documentation for Scanner, there is no method to change input sources. Thankfully, Java has a neat little class called SequenceInputStream。这使您可以将两个输入流合并为一个。它从第一个输入流读取直到完全耗尽,然后切换到第二个输入流。我们可以使用它从一个文件中读取,然后切换到第二个文件,所有这些都在一个输入流中。以下是如何执行此操作的示例:

// 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);
}

这将产生如下内容:

Content
of
file
1

Content
of
file
2

现在您实际上只创建了一个 Scanner 对象,并使用它从两个不同的文件读取输入。

注意:我在上面的代码片段中省略了所有异常处理以减少样板代码,因为问题不是明确地关于异常。我假设你知道如何自己处理异常。