20 java csv serialization object
我想将一个Object写入CSV文件.对于XML,我们有XStream的像这样
所以,如果我想对象转换为CSV我们有任何这样的图书馆吗?
编辑: 我想将我的Bean列表传递给一个方法,该方法应该将bean的所有字段写入CSV.
Niv*_*vas 21
首先,序列化是将对象"原样"写入文件.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){}
}
Run Code Online (Sandbox Code Playgroud)
这是产品(为了便于阅读而隐藏了getter和setter):
class Product
{
private long id;
private String name;
private double costPrice;
private boolean vatApplicable;
}
Run Code Online (Sandbox Code Playgroud)
这就是我测试的方式:
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);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
干杯.
为了方便 CSV 访问,有一个名为OpenCSV的库。它确实可以轻松访问 CSV 文件内容。
编辑
根据您的更新,我认为以前的所有回复都是不正确的(由于它们的级别低)。然后,您可以采用完全不同的方式,实际上是休眠方式!
通过使用CsvJdbc驱动程序,您可以加载您的 CSV 文件作为 JDBC 数据源,然后将您的 bean 直接映射到此数据源。
我会和你谈论CSVObjects,但由于该站点似乎已损坏,我担心现在该库不可用。
归档时间: |
|
查看次数: |
83150 次 |
最近记录: |