【发布时间】:2018-07-11 10:23:59
【问题描述】:
我得到的只是哈希图的地址,文件写入器不起作用,我已经尝试了所有方法:扫描仪、缓冲写入器、重写 write() 方法。
public class hmapTest implements java.io.Serializable {
public static void main(String[] args) {
HashMap<Integer, String> hmap3 = new HashMap<Integer, String>();
// add elements to hashmap
hmap3.put(1, "to");
hmap3.put(2, "in");
hmap3.put(3, "at");
hmap3.put(4, "on");
hmap3.put(5, "under");
try {
FileOutputStream fos = new FileOutputStream("hashser.txt");
ObjectOutputStream ous = new ObjectOutputStream(fos);
ous.writeObject(hmap3);
ous.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
输出:
¬í¬íloadFactorI 等
【问题讨论】:
-
应该是人类可读的形式,还是只是序列化以供以后反序列化?
-
人类可读的 txt(csv 等),例如:
1 to 2 in等等。当然,下一步就是从一个txt或者一个csv中读取到一个hasmap列表中显示在控制台中 -
HashMap转文本并不难,但Properties提供开箱即用的读+写功能:.properties 和 XML 都适用。 -
序列化流不是文本。因此,它们不应保存在扩展名为
.txt的文件中。 -
谢谢大家,我明白了,txt文件中的指针只是存储hashmap数据,如果考虑到qs,只能使用ObjectInputStream通过一些代码在控制台中显示多余的应该删除
标签: java object collections hashmap