0

How can I write and read ListMultimap to file using Properties?

I have an index as follows:

ListMultimap<Object, Object> index = ArrayListMultimap.create();

and writing index to file using Properties as follows:

writeIndexToFile(ListMultimap<Object, Object> listMultimap, String fileName) {
    Properties properties = new Properties();
    properties = MapUtils.toProperties(toMap(listMultimap));
    properties.store(new FileOutputStream(fileName),null);
}

where, toMap() method is:

Map<Object, Object> toMap(ListMultimap<Object, Object> multiMap) {
    if (multiMap == null) {
        return null;
    }
    Map<Object, Object> map = new HashMap<Object, Object>();
    for (Object key : multiMap.keySet()) {
        map.put(key, multiMap.get(key));
    }
    return map;
}

After running this code, I found the output file is empty. Why nothing is getting written into file?

in above code I cannot call directly as:

MapUtils.toProperties(listMultimap);

because listMultimap is not of type Map. So I converted it to Map using method toMap(). But still it seems that Properties is unable to get map correctly.

Note:

I tried printing listMultimap by converting it to JSON using Gson, but this also failed to convert to string. No Exception occured, but it returned empty string. Actual listMultimap is something like:

listMultiMap

where, index == listMultimap.

I'm not getting where am I going wrong.

N D Thokare
  • 1,703
  • 6
  • 35
  • 57
  • Your transformation code will not work: a `ListMultimap`'s `.get()` method return a `List`. – fge Jul 17 '13 at 11:01
  • 1
    Then is there any way to get rid of this? When I printed Class of result from `get()`, it gave me `class com.google.common.collect.AbstractMapBasedMultimap$RandomAccessWrappedList`. – N D Thokare Jul 17 '13 at 11:14
  • The problem you have is that a key can be mapped to multiple values in a `ListMultimap`, how do you want to "map" it into a "normal" map? – fge Jul 17 '13 at 11:18
  • Yah, I can see that problem. But then is there any other way by which I can write `ListMultimap` to file and read it back? – N D Thokare Jul 17 '13 at 11:23
  • I have even tried with `listMultimap.asMap()` to convert to `Map`. Still this has not written to file using `Properties`. – N D Thokare Jul 17 '13 at 11:46
  • How do you imagine writing a list to properties? I.e. `key = value` supports only one value for key, so it's difficult to say what you are trying to achieve. Also, if you used generics properluy, you would see what is the problem with your current code. – Grzegorz Rożniecki Jul 17 '13 at 13:33
  • 2
    Most ListMultimap implementations implement Serializable. Why not use that? – Louis Wasserman Jul 17 '13 at 15:54

0 Answers0