P basak
P basak

Reputation: 5004

building data structure parsing textfile java

in a text file I have following text.

add device 1: /dev/input/event7
  name:     "evfwd"
add device 2: /dev/input/event6
  name:     "aev_abs"
add device 3: /dev/input/event5
  name:     "light-prox"
add device 4: /dev/input/event4
  name:     "qtouch-touchscreen"
add device 5: /dev/input/event2
  name:     "cpcap-key"
add device 6: /dev/input/event1
  name:     "accelerometer"
add device 7: /dev/input/event0
  name:     "compass"
add device 8: /dev/input/event3
  name:     "omap-keypad"

What i need to do is that for each name element i need to extract the corresponding event number and put them on a hashmap.

for example from the text we see that name evfwd is linked with event7, so the hashmap will look like this

<"evfwd", 7>

similarly

<"compass", 0>

How can I efficiently parse the text and build a hashmap like that in java?

Upvotes: 0

Views: 166

Answers (2)

Erol
Erol

Reputation: 6526

I will go with the basics.

Write a function that reads 4 words at first and takes the 4th word. Parse the 4th word into 3 different words using "/" as a delimiter. Take the last one, read the last char and keep it as the value of hashmap.

Then go on read two more words, take the last one and store it into hashmap as the key and the value you read previously.

Apply this function recursively until you reach end of file.

Upvotes: 0

Alex Coleman
Alex Coleman

Reputation: 7326

You should probably use a regex (regular expression) to parse out the info. To use a regex, look at the Pattern and Matcher classes, here's an example:

Pattern pattern = Pattern.compile("test");
Matcher matcher = pattern.matcher("some testing thing with a test in it");

You can then call matcher.find() to set the matchers contents to the next match (it returns true if it found another one, false if it hit the end).

You need a regex with what are called capture groups, basically whenever you put ( ) around something in a regex, you can call matcher.group(index) to find the contents of those ( ) (it should be noted that .group(0) returns the whole thing, .group(1) contents of 1st ( ), etc.)

Here's a regex I just made that should work for you:

add device \d*?: /dev/input/event(\d*?)\n name: \"(.*?)\"

This says in english:

add device [some number]: /dev/input/event[some number, capture group #1]\n name: \"[some string, capture group #2]\"

To get it's event number, call Integer.parseInt(matcher.group(1)) and to get it's name, call matcher.group(2).

Tell me if anything fails, hope I helped :)

Upvotes: 4

Related Questions