Java读取文本文件并将不同的行组合在一起

时间:2017-04-28 22:46:47

标签: java

假设我们有以下文本文件,其中包含ID(非唯一),名称和编号

1 Hello 3
1 Goodbye 2
1 Hello 6
1 Goodbye 5

它们不在同一条线上,我希望能够将它们组合在一起并将其放入变量中。这些不必像这样在彼此旁边,所以如果id和name都相似则需要在if语句中添加数字。

我希望能够将此作为我的输出

Hello 9
Goodbye 7 

所以在输出任何内容之前必须读取整个文件,这将如何完成?

2 个答案:

答案 0 :(得分:0)

    File file = new File("your/file/path");
    String line = "";
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {

        while ((line = reader.readLine()) != null) {
            // the algorithm that YOU should develop
            //or fail to develop and ask about to group things etc.
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }

答案 1 :(得分:0)

这是一个快速而肮脏的解决方案,它使用Java 8 stream api和Java 7 NIO.2 api:

// read all lines from the file
Files.readAllLines(Paths.get("<path_to_your_file>"))
        // begin the stream
        .stream()
        // split every line by whitespaces
        // to get arrays like [1, "Hello", 3], [1, "Goodbye", 2]...
        .map(s -> s.split("\\s+"))
        // collecting to a map, grouping by the String {firstColumn}-{secondColumn}
        .collect(Collectors.groupingBy(split -> split[0] + "-" + split[1],
                // downstream collector sums the 3rd column after parsing them as long
                Collectors.summingLong(split -> Long.parseLong(split[2]))))
        // so we have Map<String, Long> with entries like {1-Hello -> 9}, {2-Goodbye -> 7}
        .forEach((key, value) ->
                // we print these entries one each line (println)
                // by taking the part after dash of key,
                // and a space between key and value, like: Hello 9
                System.out.println(key.split("-")[1] + " " + value));

请注意,此解决方案远未完成,例如:
1-将整个文件读入内存,因此如果文件太大,可能会导致问题(大型分配堆,OutOfMemoryError等)。如果通过流式传输完成会更好。

2-如果允许“名称”具有空格,则用空格分割将失败 - 这将需要一些额外的工作。解决方案假设每行都有3个“列”,由空格分隔。

3-如果允许“名称”具有破折号(-),则在破坏输出的同时按破折号分割会得到错误的结果。实际上,分组应该使用单独的分类器类,或TupleEntry

4-解决方案假设第3列始终是可解析的long,并且总和不超出Long的边界。

但至少它可以为您提供以下步骤。您可以通过类似的步骤正确实施。

相关问题