首先,序列化将文件“原样”写入文件. 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);
}
希望这可以帮助.
干杯.