Java导入不同数量的节点的映射

时间:2016-10-27 03:49:44

标签: java

我是Java的初学者,我想将具有不同节点的地图数据导入java。数据位于txt文件中,样本位于下方。第一行图​​形数据是节点数。以下每行包含两个整数(a,b),表示从节点$a$到节点$b$的边。

enter image description here

我应该使用哪种功能或扫描仪?

2 个答案:

答案 0 :(得分:0)

要从文本文件导入数据,您可以使用Scanner类。

    try {
        Scanner scanner = new Scanner(new File("[path to your file]/yourfile.txt"));
        int numOfNodes = scanner.nextInt();
        System.out.println("Printing numOfNodes : " + numOfNodes);

        //Since I will be using nextLine
        scanner.nextLine();
        //I have redundant scanner.nextLine() to read the remaining bit of the previous line
        while(scanner.hasNextLine()){
            String[] values = scanner.nextLine().split(" ");
            int a = Integer.parseInt(values[0]);
            System.out.println("Printing Edge A: " + a);
            int b = Integer.parseInt(values[1]);
            System.out.println("Printing Edge B: " + b);
            //logic for building graph will go in here
            // Edge edge = new Edge(a, b);
        }
    } catch (Exception ex) {
        ex.printStackTrace();  
        //Whatever you want to happen
        //FileNotFoundException - check the file name and directories 
        //NumberFormatException - data is not what you think or said
    }

答案 1 :(得分:-1)

您可以使用RandomAccessFile将每行读入String,然后将String解析为您想要的内容。

File file = new File("your-file-name");
RandomAccessFile raf = new RandomAccessFile(file, "r"); // r means read access.

raf.readLine(); // will read a line of the file, and move the cursor to the next line.