java - 从文本文件中获取单行和多行值
问题描述
我使用以下Java
代码从文本文件中获取特定值,该文件包含不同顺序的键值对。
if(nfo_file.exists() && !nfo_file.isDirectory()) {
Scanner scanner = new Scanner(nfo_file);
Map<String, String> values = new HashMap<>();
String line, key = null, value = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.contains(":")) {
if (key != null) {
values.put(key, value.trim());
}
int indexOfColon = line.indexOf(":");
key = line.substring(0, indexOfColon);
value = line.substring(indexOfColon + 1);
} else {
value += " " + line;
}
}
for (Map.Entry<String, String> entry : values.entrySet()) {
if (entry.getKey().startsWith("Description")) {
nfodata[0] = entry.getValue();
}
输入文本文件示例:
Num: 10101
Name: File_8
Description: qwertz qwertz
qwertz (qwertz) ztrewq?
Neque porro quisquam est qui
Quantity: 2
在某些情况下它不起作用,它不读取一个衬里,有时只读取多行值的第一行。
解决方案
看起来您的代码不会将最后一个键值对添加到Map
.
尝试:
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.contains(":")) {
if (key != null) {
values.put(key, value.trim());
key = null;
value = null;
}
int indexOfColon = line.indexOf(":");
key = line.substring(0, indexOfColon);
value = line.substring(indexOfColon + 1);
} else {
value += " " + line;
}
}
if (key != null) {
values.put (key, value.trim());
}
推荐阅读
- ios - Swift 5.1 错误:[插件] AddInstanceForFactory:没有为 id 注册工厂
- r - 用于生成表格的 R 包
- jenkins-pipeline - Jenkins Groovy 管道在通过先前测试的电子邮件中显示失败的测试
- entity-framework - EF Core Remove-Migration 删除的不仅仅是最近的迁移
- java - 如何用两个键盘键终止 java 程序?
- reactjs - 如何设置变量函数的状态
- r - 从 pdf 文件中读取 QR
- python - Python - 每次调用后向变量添加一个
- terraform - 在 gcp 监控过滤器中使用正则表达式
- svg - 如何缩放 svg