【问题标题】:How can I write an object into a txt or csv file with?如何将对象写入 txt 或 csv 文件?
【发布时间】: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


【解决方案1】:

如果你只需要一个任意的人类可读的形式,你可以这样做:

class Main {

    public static void main(String[] args) throws FileNotFoundException {

        HashMap<Integer, String> hmap = new HashMap<>();
        hmap.put(1, "to");
        hmap.put(2, "in");
        hmap.put(3, "at");
        hmap.put(4, "on");
        hmap.put(5, "under");

        try (XMLEncoder stream = new XMLEncoder(new BufferedOutputStream(System.out))) {
            stream.writeObject(hmap);
        }
    }
}

然而,如果它必须是 CSV,你必须使用第三方库(例如https://poi.apache.org/),或者自己实现它。此外,如果您的数据只是映射到值的连续整数列表,请考虑使用List 而不是HashMap

【讨论】:

  • 谢谢,因为我是初学者,我不太了解这些工具的工作方式,例如,我绝对无法自己实施您的任何建议(除非我花费我的余生都在尝试),但是,您的代码会在控制台中显示某些内容,但不会在 csv 文件中显示。在现实生活中,我想我将不得不使用数据库并写入/读取以前存储在另一个表(csv 或 txt)中的 hashmap 中的键和值。再次感谢您的宝贵时间和意见。
猜你喜欢
  • 2013-10-04
  • 2015-06-29
  • 2023-03-22
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
相关资源
最近更新 更多