我正在尝试使用以下代码将哈希集(整数)导出到文件,但我似乎无法使用 outputStream.write()
来执行此操作。在这里或谷歌上似乎没有任何以前的问题涵盖它,这让我感到惊讶。
Hashset 在 Activity 中定义为:
HashSet<Integer> set = new HashSet<Integer>();
方法是:
public void savehashset(){
String filename="storedhashset.set";
File storedhashset = new File(getFilesDir(), filename);
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(set);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
最佳答案
您正在尝试在文件上序列化您的 HashSet
。为此,您可以使用 ObjectOutputStream
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(set);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
来自 writeObject 的文档:
Writes an object to the target stream.
关于java - 如何在 Android 中将 Hashset 保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22017285/