java - 用换行符分割文本文件中的文本
问题描述
import java.io.*;
public class Wordcount {
public static void main(String[] args) throws Exception {
BufferedReader in = null;
String[] splited = null;
try {
in = new BufferedReader(new FileReader("sample.txt"));
String read = null;
while ((read = in.readLine()) != null) {
splited = read.split("systemSerialNumber:");
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
in.close();
}
System.out.println(splited[3]);
}
}
“sample.txt”文件包含以下文本。
"2018-10-16 19:54:26.691 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1 - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.074 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1 - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.293 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1 - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.296 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1 - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
我收到数组索引超出范围异常的错误。以及为什么我得到这个异常,即使在拆分后我也不知道所有文本文件数据都存储在数组的一个索引中。剩下的都是空的。
堆栈跟踪 :
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at Task1.Wordcount.main(Wordcount.java:29)
解决方案
检查结果的长度是否为 2。最后一行可能为空。
Path path = Paths.get("sample.txt");
Files.lines(path, Charset.defaultCharset())
.forEach(line -> {
String[] splitted = read.split("systemSerialNumber:");
if (splitted.length == 2) {
...
}
});
作为无关信息:
String[] splitted = read.split("systemSerialNumber:", 2);
将结果限制为最多 2 个元素,以防"systemSerialNumber:"
出现不止一次。
推荐阅读
- c# - EFCore:在 SaveChanges() 期间由于 fk 对象不存在而导致 fk 约束失败时该怎么办
- tensorflow - 如何在张量流中重复张量元素可变次数
- java - 将字符串 [] 转换为整数 []
- java - 如何读取 Zip 文件中的 Zip 文件中的文件内容
- reactjs - 当 url 在反应 Navlink 中启动字符串时,我可以添加活动类吗?
- django - 在 Django 中删除模型项时如何执行自定义 SQL 查询?
- angular - 模块“app.module.ts”声明的意外值“DoughnutChartComponent indoughnutChart.component.d.ts”
- sql-server - 在两个单独的 ADFv2 管道完成后执行脚本
- sql - 选择不同行中的列必须具有完全相同的值的行
- python - AttributeError: __enter__ 在连接到 mysql 数据库期间