我有一个Hashtable<String, String>table
包含要存储在文本文件中的数据,我将其存储为Object
,如下所示:
Hashtable<String, String>table1=new Hashtable<String,String>();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(table1);
oos.close();
fos.close();
然后我尝试像Object
那样读它,就像我这样存储它一样:
Hashtable<String, String>table2=new Hashtable<String,String>();
FileInputStream reader=new FileInputStream(file);;
ObjectInputStream buffer=new ObjectInputStream(reader);
Object obj=buffer.readObject();
table2=(Hashtable<String, String>)obj;
buffer.close();
reader.close();
但问题是table2
仍为空!我认为问题在于阅读方式,请采用任何有用的阅读方式吗?
答案 0 :(得分:1)
我建议您使用HashMap<String, String>
代替Hashtable<String, String>
并编程到Map<String,String>
界面,我还建议您使用try-with-resources
,最后确保存储内容在序列化之前你的Collection
。
File f = new File(System.getProperty("user.home"), "test.ser");
Map<String, String> table1 = new HashMap<>();
table1.put("Hello", "world");
try (FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(table1);
} catch (Exception e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);) {
Map<String, String> table = (Map<String, String>) ois.readObject();
System.out.println(table);
} catch (Exception e) {
e.printStackTrace();
}
输出
{Hello=world}