java - Android - 将 Map<String, Object[]> 保存到文件

标签 java android file hashmap

如何将这种 map 保存到文件中? (它也应该适用于安卓设备)
我试过了:

        Properties properties = new Properties();

        for (Map.Entry<String, Object[]> entry : map.entrySet()) {
            properties.put(entry.getKey(), entry.getValue());
        }

        try {
            properties.store(new FileOutputStream(context.getFilesDir() + MainActivity.FileName), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
我得到:
class java.util.ArrayList cannot be cast to class java.lang.String (java.util.ArrayList and java.lang.String are in module java.base of loader 'bootstrap')
我应该怎么办?

最佳答案

我正在写一个基于 String 的答案当我意识到您的错误可能某个值可能是 ArrayList 时,值序列化... 老实说,我并不完全理解错误背后的原因(当然,这是一个类型转换,但我不明白 java.util.ArrayList 部分)...
无论如何,当您尝试存储属性并尝试转换您的 Object[] 时,就会出现问题。至String为了节省。
在我原来的回答中,我建议您手动 join生成文件时的值。 join 很简单String 的方法类(class):

Properties properties = new Properties();

for (String key : map.keySet()) {
  Object[] values = map.get(key);
  // Perform null checking
  String value = String.join(",", values);
  properties.put(key, value);
}

try {
  properties.store(new FileOutputStream(context.getFilesDir() + MainActivity.FileName), null);
} catch (IOException e) {
  e.printStackTrace();
}
要阅读您的值(value)观,您可以使用 split :
Properties properties = new Properties();
Map<String, String> map = new HashMap<>();

InputStream in = null;
try {
  in = new FileInputStream(context.getFilesDir() + MainActivity.FileName);
  properties.load(in);

  for (String key : properties.stringPropertyNames()) {
    String value = properties.getProperty(k);
    // Perform null checking
    String[] values = value.split(",");
    map.put(key, value);
  }
} catch (Throwable t) {
  t.printStackTrace();
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
但我认为您有一个更好的方法:请使用 Java 内置的序列化机制来保存和恢复您的信息。
为了保存您的 map使用 ObjectOutputStream :
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(context.getFilesDir() + MainActivity.FileName))){
  oos.writeObject(map);
}
您可以阅读您的 map返回如下:
Map<String, Object> map;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(context.getFilesDir() + MainActivity.FileName))){
  map = (Map)ois.readObject();
}
如果您的 map 中存储的所有对象是 Serializable s 这第二种方法要灵活得多,并且不限于String。像第一个一样的值。

关于java - Android - 将 Map<String, Object[]> 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68273723/

相关文章:

android - 无法从特定设备(MI 设备)的收件箱中读取所有 SMS

python - H5py:以写入模式重新打开文件会删除以前的数据

arrays - 使用swift读入文本文件

java - 缓存文件输入流

java - 正则表达式字符串中的多个IP地址

android - 使用蓝牙鼠标/演示器控制 Android 应用程序

c - lstat 返回 <0

Java - 如何在同一个类的不同静态方法中共享对象

java - Struts <bean :cookie> tag breaks on WebLogic 11gR1

Android 上的 Java FileInputStream/Scanner 问题