如何将这种 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/