栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将对象序列化为CSV文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将对象序列化为CSV文件?

首先,序列化是将对象“按原样”写入文件。AFAIK,您不能选择文件格式和全部。序列化的对象(在文件中)具有自己的“文件格式”

如果要将对象(或对象列表)的内容写入CSV文件,则可以自己完成,这并不复杂。

看起来Java CSV库可以做到这一点,但是我自己还没有尝试过。

编辑 :请参阅以下示例。这绝不是万无一失的,但是您可以在此基础上构建。

    //European countries use ";" as     //CSV separator because "," is their digit separator    private static final String CSV_SEPARATOR = ",";    private static void writeToCSV(ArrayList<Product> productList)    {        try        { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8")); for (Product product : productList) {     StringBuffer oneLine = new StringBuffer();     oneLine.append(product.getId() <=0 ? "" : product.getId());     oneLine.append(CSV_SEPARATOR);     oneLine.append(product.getName().trim().length() == 0? "" : product.getName());     oneLine.append(CSV_SEPARATOR);     oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice());     oneLine.append(CSV_SEPARATOR);     oneLine.append(product.isVatApplicable() ? "Yes" : "No");     bw.write(oneLine.toString());     bw.newline(); } bw.flush(); bw.close();        }        catch (UnsupportedEncodingException e) {}        catch (FileNotFoundException e){}        catch (IOException e){}    }

这是产品(为便于阅读,隐藏了获取器和设置器):

class Product{    private long id;    private String name;    private double costPrice;    private boolean vatApplicable;}

这就是我测试的方式:

public static void main(String[] args){    ArrayList<Product> productList = new ArrayList<Product>();    productList.add(new Product(1, "Pen", 2.00, false));    productList.add(new Product(2, "TV", 300, true));    productList.add(new Product(3, "iPhone", 500, true));    writeToCSV(productList);}

希望这可以帮助。

干杯。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号