gpt4 book ai didi

java - 从文件中读取多行到单个字符串

转载 作者:行者123 更新时间:2023-12-02 10:43:17 24 4
gpt4 key购买 nike

我有一个文件,其中的行具有特定的前缀。在某些情况下,某些类型的数据位于多行中,例如在此文件示例中:

Num: 10101
Name: File_8
Description: qwertz qwertz
qwertz qwertz ztrewq
Quantity: 2

属性的顺序(编号、名称、描述、数量)未定义。我使用以下代码从文件读取数据并将其存储到数组。

BufferedReader abc = new BufferedReader(new FileReader(file));
while ((strLine = abc.readLine()) != null) {
if(strLine.startsWith("Name:")){
data[0] = strLine.substring(strLine.indexOf(" ")+1);
data[0].trim();
}
}

前缀之间的字符串应存储在字符串中。

最佳答案

使用java.util.Scanner

捕获映射:

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;
}
}
values.put(key, value.trim());

for (Map.Entry<String, String> mapEntry: values.entrySet()) {
System.out.println(mapEntry.getKey() + " -> '" + mapEntry.getValue() + "'");
}

打印:

Description -> 'qwertz qwertz qwertz qwertz ztrewq'
Num -> '10101'
Quantity -> '2'
Name -> 'File_8'

关于java - 从文件中读取多行到单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com