views:

147

answers:

2

I want to write a Object into CSV file. For XML we have XStream like this
So if i want to convert object to CSV do we have any such library ?

EDIT: I want to pass my list of Bean to a method which should write all the fields of bean to CSV.

+1  A: 

First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its 'own file format'

If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.

Looks like Java CSV Library can do this, but I have not tried this myself.

EDIT: See following sample. This is no way foolproof, but you can build on this.

    //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){}
    }

This is product (getters and setters hidden for readability on SO):

class Product
{
    private long id;
    private String name;
    private double costPrice;
    private boolean vatApplicable;
}

And this is how I tested:

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);
    }

Hope this helps.

Cheers.

Nivas
+1 writing is really simple, reading is a bit more difficult but not so much... and if there is no new line inside the output values the reading become really simple...
Vinze
doesn't satisfy my requirement
NewBeee_Java
@NewBie_Java: If Java CSV Library doesn't satisfy your requirement, you can write your own logic. It is not difficult, and doesn't harm... Have added a simple logic on how to do this. Try to build on that...
Nivas
+1  A: 

For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.

Riduidel
OpenCSV doesn't satisfy my requirement
NewBeee_Java