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
它在某些情况下不起作用,它不读取单行,有时只读取多行值的第一行。