繁体   English   中英

Java,如何读取包含多行不同数字整数的.txt文件

[英]java, how to read a .txt file that have multiple lines of different numbers of integers

我有一个.txt文件,每一行都是这样的格式

1 2,10 3,20

2 6,87

该文件实际上代表一个图形,第1行表示顶点1的边指向顶点2,长度为10,顶点1也具有指向边的顶点到顶点3,长度为20。第2行表示顶点2的顶点只有一个方向。边到顶点6,长度为87。

我想做Dajkstra的最短路径算法。 我不想定义顶点类,边缘类等,相反,我想将每条线存储到二维数组中,以便通过使用索引可以获取图形信息。 如果是在python中,我会将整个文件存储到嵌套列表[[((2,10)(3,20)],[(6,87)],...]中,这样就无需创建顶点,边缘上课,我可以通过为列表建立索引来轻松访问所有必要的图形信息。

我的问题是,如何用Java做到这一点? 2-D数组不好,因为每行可能具有不同数量的整数。 ArrayList可能不错,但是如何有效地将整个txt文件读入此类arraylist?

    ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(); 

    try{

            Scanner sc = new Scanner(new File("a.txt"));               
            while(sc.hasNextLine()){
            String line= sc.nextLine();             
            ArrayList<Integer> vertex = new ArrayList<Integer>();               
            Scanner lineContents = new Scanner(line).useDelimiter("\\D"); //"\\D" means any none digit

            while (lineContents.hasNext()) {
                    vertex.add(lineContents.nextInt());
            }

            graph.add(vertex);
            lineContents.close();
        }
        sc.close();
    }

试试这个方法:

public Map<Integer, Map<Integer, Integer>> process(String filePath) throws IOException {
    Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();

    Files.lines(new File(filePath).toPath())
            .map(line -> line.split(" "))
            .map(Arrays::asList)
            .forEachOrdered(elements -> {
                int vertexId = parseInt(elements.get(0));

                Map<Integer, Integer> vertexMap = new HashMap<>();
                elements.subList(1, elements.size()).stream()
                        .map(element -> element.split(","))
                        .map(Arrays::asList)
                        .forEach(pair -> vertexMap.put(parseInt(pair.get(0)), parseInt(pair.get(1))));

                graph.put(vertexId, vertexMap);
            });


    return graph;
}

我返回了一个Map而不是List因为按索引工作是一种不好的做法,并且您获得了相同的功能。

另请注意,这未经测试-可能无法正常工作,但我认为可以。

暂无
暂无

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

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