如何将对象写入txt或csv文件?

时间:2018-02-01 06:51:09

标签: java object collections hashmap

所有我得到的是hashmap的地址,filewriter不起作用,我已经尝试了一切:scan,bufferedwriter,重写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等

1 个答案:

答案 0 :(得分:0)

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

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

相关问题