在文件</object,>中编写和读取ListMultimap <object,object =“”>

时间:2013-07-17 14:20:15

标签: java file-io guava multimap

我尝试使用ListMultimapProperties写入文件,但似乎不可能,请参阅问题Writing and reading ListMultimap to file using Properties

继续,如果使用Properties存储ListMultimap的方法不正确,我们如何将ListMultimap存储到文件中?我们怎样才能从文件中读回来?

e.g。让我说我有:

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

如何编写将此ListMultimap写入文件并从文件中读回的方法:

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

ListMultimap readFromFile(String filePath){
    ListMultimap multiMap;
    //multiMap = read from file
    return multiMap;
}

1 个答案:

答案 0 :(得分:2)

您需要决定如何表示文件中的每个对象。例如,如果您的ListMultimap包含String,您只需编写字符串值,但如果您正在处理复杂对象,则需要将这些对象的表示形式生成为byte[],如果你想使用Properties那么应该是Base64编码。

基本的读取方法应该是:

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;
}

写入方法:

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");
}

此示例使用您需要根据您的要求定义的serializedeserialize方法,但签名包括:

public String serialize(Object object)

public Object deserialize(String s)