【问题标题】:Read multiple lines from file to a single string从文件中读取多行到单个字符串
【发布时间】:2018-10-12 10:49:23
【问题描述】:

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

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();
       }
    }

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

【问题讨论】:

  • 你能澄清你想要达到的目标吗?你问题的最后一句话有点不清楚。
  • @Skere :我更新了问题。 DescriptionQuantity 的示例:desc 变量的值应为 qwertz qwertz qwertz qwertz ztrewq
  • desc 变量???
  • @Maurice :我对每个属性使用同名的变量。
  • 您要查找的词是“连接”。

标签: java bufferedreader filereader


【解决方案1】:

使用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'

【讨论】:

  • 属性顺序(数量、名称、描述、数量)未定义。
【解决方案2】:

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

如果将内容读入数组,可以使用join:

String.join(delimiter, elements);

例如。带有分隔符, 和一个数组:

String str = String.join(",", new String[]{"1st line", "2nd line", "3rd line"});

产生输出: 1st line,2nd line,3rd line


或者直接读取到字符串:

// assume we have a function
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);

【讨论】:

  • 末尾没有任何预定义的分隔符。
【解决方案3】:

好的,所以传递给 data[0] 的所有内容都应该连接成一个字符串?为什么不这样使用 StringBuilder 类呢?

StringBuilder stringBuilder = new StringBuilder();
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();
        stringBuilder.append(data[0]);
       }
    }

【讨论】:

  • 我明白了,但这不是从文件中读取多行到单个字符串的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多