Вопрос

I tried writing ListMultimap to file using Properties, but it seems impossible, refer to question Writing and reading ListMultimap to file using Properties.

Going ahead, if using Properties to store ListMultimap is not correct way, how can we store ListMultimap into a file? And how can we read back from file?

e.g. lets say I have:

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

How can I write methods to write this ListMultimap to file and read back from file:

writeToFile(ListMultimap multiMap, String filePath){
    //??
}

ListMultimap readFromFile(String filePath){
    ListMultimap multiMap;
    //multiMap = read from file
    return multiMap;
}
Это было полезно?

Решение

You need to decide how you will represent each object in the file. For example, if your ListMultimap contained Strings you could simply write the string value but if you're dealing with complex objects you need to produce a representation of those object as a byte[], which if you want to use Properties should then be Base64 encoded.

The basic read method should be something like:

public ListMultimap<Object, Object> read(InputStream in) throws IOException
{
  ListMultimap<Object, Object> index = ArrayListMultimap.create();

  Properties properties = new Properties();
  properties.load(in);

  for (Object serializedKey : properties.keySet())  
  {
    String deserializedKey = deserialize(serializedKey);
    String values = properties.get(serializedKey);

    for (String value : values.split(",")) 
    {
      index.put(deserializedKey, deserialize(value)); 
    }
  }

  return index;
}

And the write method this:

public void write(ListMultimap<Object, Object> index, OutputStream out) throws IOException
{
  Properties properties = new Properties();

  for (Object key : index.keySet())
  {
    StringBuilder values = new StringBuilder();

    for (Object value = index.get(key))
    {
      values.append(serailize(value)).append(",");
    } 

    properties.setProperty(serailize(key), values.subString(0, values.length - 1));
  }

  properties.store(out, "saving");
}

This example makes use of serialize and deserialize methods that you'll need to define according to your requirements but the signatures are:

public String serialize(Object object)

and

public Object deserialize(String s)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top