【问题标题】:Can you use one scanner object to read more than one file?您可以使用一个扫描仪对象来读取多个文件吗?
【发布时间】:2021-01-27 22:20:15
【问题描述】:

我想知道我是否可以创建一个 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 对象只能从一个源获取输入。但是,您可以创建一个SequenceInputStream,它可用于从多个文件中获取输入并将其全部组合到一个输入流中,然后您的 Scanner 可以从中读取。
  • 您可以做任何您想做的事,尽管您正在创建第二个扫描仪。您应该在覆盖引用之前关闭第一个。
  • 为什么要这样做?没有任何好处,只会使您的代码复杂化。

标签: java io java.util.scanner


【解决方案1】:

您可以通过两种不同的方式做到这一点。一种是简单地制作一个新的 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,则无法更改输入源。值得庆幸的是,Java 有一个简洁的小类,名为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 对象,并使用它从两个不同的文件中读取输入。

注意:我在上面的代码 sn-ps 中省略了所有异常处理以减少样板代码,因为问题没有明确涉及异常。我假设您知道如何自己处理异常。

【讨论】:

  • 我知道如何处理异常,谢谢大家的帮助!
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 2013-12-04
  • 2014-05-08
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多