Java - 逐行读取文件直到文件末尾

问题描述 投票:1回答:2

我正在开发一个项目,要求我在Java中找到给定图形的最小生成树。我非常喜欢Java noob,因为我主要使用C ++。

我编写了算法,但是有一种独特的输入格式,有点像这样:

0 1:33 2:0 3:12 4:29 5:32 6:22 7:13 8:45 9:21
1 0:6 2:18 3:2 4:26 5:41 6:8 7:47 8:13 9:19
2 0:22 1:28 3:49 4:47 5:5 6:16 7:32 8:5 9:34
3 0:21 1:24 2:2 4:29 5:20 6:39 7:17 8:21 9:3
4 0:27 1:20 2:38 3:4 5:14 6:25 7:0 8:24 9:11
5 0:20 1:7 2:29 3:15 4:3 6:19 7:11 8:19 9:41
6 0:14 1:36 2:6 3:45 4:18 5:33 7:43 8:22 9:36
7 0:25 1:12 2:15 3:45 4:18 5:43 6:41 8:37 9:26
8 0:29 1:44 2:23 3:15 4:34 5:45 6:27 7:29 9:4
9 0:18 1:41 2:20 3:25 4:18 5:10 6:10 7:49 8:42

或者,更清楚地说:

[source-vertex] [destination-vertex]:[weight] [destination-vertex]:[weight] ...

我想知道的是如何阅读这种输入格式?

我想读取每一行,直到文件结束,然后解析每行的数字。

java file input graph format
2个回答
2
投票

所以你基本上有两个问题:

  • 如何逐行读取文件:有很多方法可以做到这一点(Java8 +中的一些便利API),经典的方法是使用try-with-resources获取Reader并使用属性文本编码从InputStream读取。
  • 如何阅读结构化数据:最简单的方法是使用正则表达式来提取数据。

根据您的格式读取数据的代码:

File f = ... // file to read

try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8))) {

    // regular expression checking the format of each line
    Pattern linePattern = Pattern.compile("(\\d+)(?:\\s+(\\d+):(\\d+))*");
    // regular expression to find the index (first number) in a line
    Pattern indexPattern = Pattern.compile("(\\d+)");
    // regular expression to find the vertices (a:b) in a line
    Pattern relationPattern = Pattern.compile("(\\d+):(\\d+)");

    String line;
    while ((line = reader.readLine()) != null) {

        if (linePattern.matcher(line).matches()) {

            Matcher indexMatcher = indexPattern.matcher(line);
            if (indexMatcher.find()) {
                int sourceVertex = Integer.parseInt(indexMatcher.group(1));
                // do something with the sourceVertex 

                Matcher relationMatcher = relationPattern.matcher(line);
                while (relationMatcher.find()) {
                    int destinationVertex = Integer.parseInt(relationMatcher.group(1));
                    int weight = Integer.parseInt(relationMatcher.group(2));
                    // do something with destinationVertex and weight
                }
            }
        }
    }
}

0
投票

我建议使用Steam API并使用BuferedReader加载文件并唱出lines()方法。这会生成一个Stream,然后您可以根据需要进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.