繁体   English   中英

我怎样才能对象写入一个txt或者csv文件用?

[英]How can I write an object into a txt or csv file with?

我得到的只是哈希映射的地址,文件编写器不起作用,我已经尝试了所有方法:扫描器,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等

如果您只需要一种易于理解的人类可读形式,则可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM