我想将一个对象写入 CSV 文件。
对于 XML,我们有 XStream,如 this
因此,如果我想将对象转换为 CSV,我们有没有这样的库?
编辑: 我想将我的 Bean 列表传递给应该将 bean 的所有字段写入 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<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){}
}
这是产品(为便于阅读而隐藏的 getter 和 setter):
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);
}
希望这会有所帮助。
干杯。
关于java - 如何将对象序列化为 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666007/