繁体   English   中英

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

[英]Read multiple lines from file to a single string

我有一个文件,其中各行都有特定的前缀。 在某些情况下,某些类型的数据会多行显示,例如以下文件示例:

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'

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

如果将内容读入数组,则可以使用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);

好的,所以传递给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]);
       }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM