我想要将一个对象写入CSV文件。对于XML,我们有像this这样的XStream
所以,如果我想将object转换为CSV,我们有这样的库吗?
我想把我的Bean列表传递给一个方法,这个方法应该把bean的所有字段都写到CSV。
发布于 2010-09-08 08:52:41
首先,序列化是将对象“按原样”写入文件。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){}
}
这是product (为提高可读性而隐藏的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);
}
希望这能有所帮助。
干杯。
发布于 2010-09-08 08:54:12
为了方便CSV访问,有一个名为OpenCSV的库。它确实简化了对CSV文件内容访问。
编辑
根据您的更新,我认为所有以前的回复都是不正确的(由于它们的级别较低)。然后你可以用一种完全不同的方式,实际上是hibernate的方式!
通过使用CsvJdbc驱动程序,您可以加载您的CSV文件作为JDBC数据源,然后将bean直接映射到此数据源。
我本想和你谈谈CSVObjects的,但由于这个网站似乎出了问题,我担心现在库不能用了。
发布于 2012-01-19 21:47:55
拥有csv序列化程序会很有趣,因为与其他序列化方法相比,它占用的空间最小。
对java对象最接近csv的支持是spring utils项目提供的stringutils。
arrayToCommaDelimitedString(Object[] arr),但它远不是一个序列化程序。
下面是一个简单的实用程序,它使用反射来序列化值对象
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
下面是一个示例值对象
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
和运行实用程序的代码
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
输出:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
https://stackoverflow.com/questions/3666007
复制相似问题