如何将对象序列化为 CSV 文件? [英] How to serialize object to CSV file?

查看:46
本文介绍了如何将对象序列化为 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象写入 CSV 文件.对于 XML,我们有 XStream,例如 this
因此,如果我想将对象转换为 CSV,我们有这样的库吗?

我想将我的 Bean 列表传递给一个方法,该方法应该将 bean 的所有字段写入 CSV.

解决方案

首先,序列化是将对象按原样"写入文件.AFAIK,您不能选择文件格式等等.序列化对象(在文件中)有自己的文件格式"

如果你想把一个对象的内容(或者一个对象的列表)写入一个CSV文件,你可以自己做,应该不会很复杂.

看起来 Java CSV Library 可以做到这一点,但我自己没有尝试过.>

编辑:请参阅以下示例.这绝不是万无一失的,但您可以以此为基础.

//欧洲国家使用;";作为//CSV 分隔符,因为,";是他们的数字分隔符私有静态最终字符串 CSV_SEPARATOR = ",";private static void writeToCSV(ArrayList productList){尝试{BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8"));对于(产品产品: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){}}

这是产品(为了便于阅读而隐藏了 getter 和 setter):

class 产品{私人长ID;私人字符串名称;私人双成本价格;私有布尔增值税适用;}

这就是我测试的方式:

public static void main(String[] args){ArrayList<产品>productList = new ArrayList();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);}

希望这会有所帮助.

干杯.

I want to write a Object into CSV file. For XML we have XStream like this
So if i want to convert object to CSV do we have any such library ?

EDIT: I want to pass my list of Bean to a method which should write all the fields of bean to CSV.

解决方案

First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its own 'file format'

If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.

Looks like Java CSV Library can do this, but I have not tried this myself.

EDIT: See following sample. This is by no way foolproof, but you can build on this.

    //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){}
    }

This is product (getters and setters hidden for readability):

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

And this is how I tested:

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);
}

Hope this helps.

Cheers.

这篇关于如何将对象序列化为 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆