java - 您可以使用一个扫描仪对象来读取多个文件吗?
问题描述
我想知道我是否可以创建一个 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 对象从多个文件中读取的问题,因此从技术上讲,上述代码并不能回答您的问题。如果您查看 Scanner 的文档,则无法更改输入源。幸运的是,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 对象,并使用它从两个不同的文件中读取输入。
注意:我在上面的代码片段中省略了所有异常处理以减少样板代码,因为问题没有明确涉及异常。我假设您知道如何自己处理异常。
推荐阅读
- python - 在python中将参数从一个类带到另一个类
- django - 如何在 Django 我们应用程序中为 mongoDB 连接配置 settings.py
- asp.net-core - 如何防止通过 IHttpClientFactory 的 HttpClient 登录到 ILogger?
- sql-server - SQL Server 2008 R2 - 在 Lag / CTE 中考虑前一天 - 使用上一行或下一行的值
- swift - 每秒调用多次的函数中的延迟代码
- python - 在 for 循环中从列表中解压缩多个参数
- c# - 上传文件从邮递员那里工作,但不是通过代码
- scala - 可以在 spark 中处理多字符分隔符
- javascript - 使用 node.js 检查 mysql 表
- c# - 每个具有多个 azure 功能的解决方案的通用配置文件问题