【问题标题】:How to convert Map to Bytes and save to internal storage如何将 Map 转换为 Bytes 并保存到内部存储
【发布时间】:2011-12-15 08:45:07
【问题描述】:

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

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

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

【问题讨论】:

    标签: java android file-io


    【解决方案1】:
    1. 在 java 中使用序列化可以轻松解析任何可序列化的 对象到字节流。尝试使用 ObjectInputStream 和 ObjectOutputStream。

    2. 使用 json 恢复。您可以使用 google-gson 转换 Java 对象转为 JSON,反之亦然。

    3. 在 android 中使用 Parcel。 android.os.Parcel 类旨在传递数据 android(activity, service) 中的组件之间,但您仍然可以使用它来进行数据持久化。 请记住不要将数据发送到互联网,因为不同 平台可能有不同的算法来进行解析。

    我写了一个序列化的demo,试试看。

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

    【讨论】:

      【解决方案3】:

      要么像 faylon 提到的那样序列化,要么实现你自己的机制来保存和加载你的地图。通过保存,您可以遍历所有元素并保存键值对。通过加载,您将它们添加回来。实现您自己的机制的好处是,当您的程序与另一个 Java 版本一起使用时,您仍然可以使用您的持久值。

      【讨论】:

        猜你喜欢
        • 2021-02-03
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        • 2020-06-30
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多