Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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'</p> <p>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.</p> <p>Looks like <a href="http://sourceforge.net/projects/javacsv/" rel="noreferrer">Java CSV Library</a> can do this, but I have not tried this myself.</p> <p><strong>EDIT</strong>: See following sample. This is by no way foolproof, but you can build on this.</p> <pre><code> //European countries use ";" as //CSV separator because "," is their digit separator private static final String CSV_SEPARATOR = ","; private static void writeToCSV(ArrayList&lt;Product&gt; 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() &lt;=0 ? "" : product.getId()); oneLine.append(CSV_SEPARATOR); oneLine.append(product.getName().trim().length() == 0? "" : product.getName()); oneLine.append(CSV_SEPARATOR); oneLine.append(product.getCostPrice() &lt; 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){} } </code></pre> <p>This is product (getters and setters hidden for readability):</p> <pre><code>class Product { private long id; private String name; private double costPrice; private boolean vatApplicable; } </code></pre> <p>And this is how I tested:</p> <pre><code>public static void main(String[] args) { ArrayList&lt;Product&gt; productList = new ArrayList&lt;Product&gt;(); 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); } </code></pre> <p>Hope this helps.</p> <p>Cheers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload