gpt4 book ai didi

java - 如何将 Map 转换为 Bytes 并保存到内部存储

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:57 25 4
gpt4 key购买 nike

如何转换我的 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转换成正确的格式,然后在需要再次加载时将其解码回原始格式。我需要每周重新创建一次此文件,并在应用程序启动时加载它。

最佳答案

  1. 在 java 中使用序列化,您可以轻松解析任何可序列化的对象到字节流。尝试使用 ObjectInputStream 和对象输出流。

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

关于java - 如何将 Map 转换为 Bytes 并保存到内部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8517323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com