如何将映射转换为字节并保存到内部存储

2022-09-04 01:12:14

如何将>转换为 ,然后将其写入内部存储?我目前有:Map<Integer, Stringbyte[]

        try {
            FileOutputStream fos = context.openFileOutput(Const.FILE_CATEGORIES, Context.MODE_PRIVATE);
            fos.write(null);
        } catch (FileNotFoundException e) {
            // reload and create the file again
        }

但。。我不知道如何将其转换为正确的格式,然后在需要再次加载时将其解码回原始格式。我需要每周重新创建一次此文件,并在应用程序启动时加载它。Map


答案 1
  1. 使用Java中的序列化,您可以轻松地将任何可序列化的对象解析为字节流。尝试使用 ObjectInputStream 和 ObjectOuputStream。

  2. 使用 json 进行还原。您可以使用google-gson将Java对象转换为JSON,反之亦然。

  3. 在安卓中使用包裹。类 android.os.Parcel 被设计为在 android(活动、服务)中的组件之间传递数据,但您仍然可以使用它来执行数据持久性。请记住,不要将数据发送到互联网,因为不同的平台可能有不同的算法来进行解析。

我写了一个序列化的演示,试一试。

public static void main(String[] args) throws Exception {
    // Create raw data.
    Map<Integer, String> data = new HashMap<Integer, String>();
    data.put(1, "hello");
    data.put(2, "world");
    System.out.println(data.toString());

    // Convert Map to byte array
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(byteOut);
    out.writeObject(data);

    // Parse byte array to Map
    ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
    ObjectInputStream in = new ObjectInputStream(byteIn);
    Map<Integer, String> data2 = (Map<Integer, String>) in.readObject();
    System.out.println(data2.toString());
}

答案 2

我知道我正在订阅一个旧线程,但它在我的谷歌搜索中弹出。所以我将把我的5美分留在这里:

您可以使用 org.apache.commons.lang3.SerializationUtils,它有以下两种方法:

/**
 * Serialize the given object to a byte array.
 * @param object the object to serialize
 * @return an array of bytes representing the object in a portable fashion
 */
public static byte[] serialize(Object object);

/**
 * Deserialize the byte array into an object.
 * @param bytes a serialized object
 * @return the result of deserializing the bytes
 */
public static Object deserialize(byte[] bytes);