Nate Cook3
Nate Cook3

Reputation: 596

Load Dictionary Text File Into Java

I need to load a text file of information into Java. The Text file looks like this

"reproduce": {
    "VB": 7
}, 
"drill": {
    "VB": 8, 
    "NN": 16
}, 
"subgross": {
    "JJ": 2
}, 
"campsites": {
    "NNS-HL": 1, 
    "NNS": 1
}, 
"streamed": {
    "VBN": 1, 
    "VBD": 2
}

It is basically a huge collection of words with some tags included. I need to save this information in some sort of Java data-structure so that the program can search and retrieve tag statistics for a given word.

From what I've read, using a type of HashMap would be the best idea? Something like:

Map<KeyType, List<ValueType>>

Is that a good idea? How would I go about scanning this data from the text file? I could probably find a way to print the dictionary to the text file that would be easier to scan into Java.

Upvotes: 0

Views: 3176

Answers (1)

miku
miku

Reputation: 188104

While your input does not look exactly like JSON, you might be able to preprocess[1] it in a simple way to make it valid JSON. Because JSON is probably much more widespread and therefore better supported than your custom format.


If your problem then is JSON deserialization, then take a look at Jackson or Gson, which will convert your input string into objects.

Simple example in Jackson:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
Map<String,Object> data = mapper.readValue(new File("file.json"), Map.class);
// process data further here ...

Both Jackson and Gson have a lot of options and can handle complex inputs in various ways, e.g. they can serialize and deserialize from and to Maps, custom Objects, can handle polymorphism (mapping different inputs to objects of different classes) and more.


Given the input, that is currently in your question, you can simply prepend and append a curly bracket, and you would have valid JSON:

{
  "reproduce": {
    "VB": 7
  },
  "drill": {
    "VB": 8,
    "NN": 16
  },
  "subgross": {
    "JJ": 2
  },
  "campsites": {
    "NNS-HL": 1,
    "NNS": 1
  },
  "streamed": {
    "VBN": 1,
    "VBD": 2
  }
}

Upvotes: 1

Related Questions