Reading External Text File and Storing into an array

How do i read an external text file, possibly using a Scanner and store 2 values from each line into an array.

I would want to store the node id which is the first value of each line and the parent number which is the last value in each line.

The text file contains what you see below

1       2,7,|0|BLACK|NULL
10      3,4,12,|3|BLACK|3
11      4,12,|4|BLACK|4
12      8,10,11,|3|BLACK|8
2       1,3,6,8,|1|BLACK|1
3       2,4,5,6,8,10,|2|BLACK|2
4       3,5,9,10,11,|3|BLACK|3
5       3,4,8,|3|BLACK|3
6       2,3,|2|BLACK|2
7       1,8,|1|BLACK|1
8       2,3,5,7,9,12,|2|BLACK|2
9       4,8,|3|BLACK|8

Upvotes: 0

Views: 5035

Answers (2)

jrad
jrad

Reputation: 3190

Shonna, you can achieve what you want using a HashMap, a Scanner, and some simple string parsing. Here's my whole class:

import java.io.*;
import java.util.*;

public class nodes {

    private static HashMap<Integer, String> map = new HashMap<Integer, String>();

    public static void main(String[] args) {
        File file = new File("nodes.txt");
        Scanner scnr = null;
        try {
            scnr = new Scanner(file);
        } catch (FileNotFoundException e) {

        }
        while(scnr.hasNext()) {
            String line = scnr.nextLine();
            String[] getId = line.split("\\s+");
            int id = Integer.parseInt(getId[0]);
            int count = 0;
            int copy = 0;
            for(int i = 0; i < line.length(); i++) {
                if(line.charAt(i) == '|')
                    count++;
                if(count == 3) {
                    copy = i;
                    break;
                }
            }
            String parent = line.substring(copy + 1);
            map.put(id, parent);
            System.out.println(map);
        }
    }

}

What it does is it reads through each line of the file, first extracting the node id. It then cycles through each character in the line until it counts three |'s, at which point we know the rest of the line will be the parent of the node. After this is done, it pairs the id with the parent in a HashMap.

Upvotes: 0

Reimeus
Reimeus

Reputation: 159874

A regex approach (have left the array bit as an exercise for the reader):

BufferedReader br = new BufferedReader(new FileReader("hadoop_data.txt"));

String currentLine;
while ((currentLine = br.readLine()) != null) {

    Matcher matcher = Pattern.compile("(\\d+).*\\|(\\w+)").matcher(currentLine);
    if (matcher.matches()) {
        System.out.println(matcher.group(1) + "\t" + matcher.group(2));
            // add to array
    }
}

Upvotes: 2

Related Questions