java 对象转csv_java – 如何将对象序列化为CSV文件?

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

如果要将对象(或对象列表)的内容写入CSV文件,您可以自行执行,不应该很复杂.

看起来像Java CSV Library可以做到这一点,但我还没有尝试过这个.

编辑:见下面的例子.这绝对不是万无一失,但是你可以在此基础上建立.

//European countries use ";" as

//CSV separator because "," is their digit separator

private static final String CSV_SEPARATOR = ",";

private static void writeToCSV(ArrayList 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 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);

}

希望这可以帮助.

干杯.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值