-2

I am a beginner of Java and I would like to import the data of a map with different nodes into java. The data is in a txt file the sample is in below. The first line of graph data is the number of node. Each of following lines contains two integers (a, b) which represent an edge from node $a$ to node $b$.

enter image description here

Which function or scanner should I use?

nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • 1
    Possible duplicate of [Java: How to read a text file](http://stackoverflow.com/questions/2788080/java-how-to-read-a-text-file) – nbrooks Oct 27 '16 at 03:59
  • 1
    How to ask a good question: http://stackoverflow.com/help/how-to-ask You have not shown any effort trying to solve this problem. – KC Wong Oct 27 '16 at 04:04

2 Answers2

0

To import the data from a text file you can use the Scanner class.

    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
    }
Raul
  • 51
  • 3
-1

You can use RandomAccessFile to read each line into a String, and then parse the String to what you want.

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. 
T.Tony
  • 495
  • 3
  • 15