Newbie
Newbie

Reputation: 146

Trouble saving arraylist into a file

I have the following code that I call from main. The trouble with the code, it saves the products as follows: 1,ipad,499.0,ELECTRONICS

1,ipad,499.0,ELECTRONICS 2,Java Ebook,19.99,BOOK

I don't understand where the first one comes from. Can you please provide us some pointers.

Thanks a lot...

public void saveProductsToDisk() {

    String filename = "/Users/paddy/UCSC/Workspace/productDB/src/productdb/savedProducts.csv";
    BufferedWriter output = null;
    try 
    {
        output =  new BufferedWriter(new FileWriter(filename));
        StringBuffer line = new StringBuffer();
        for (Product p: getAllProducts())
        {
            line.append(p.getId() <=0 ? "" : p.getId());
            line.append(CSV_SEPARATOR);
            line.append(p.getName().trim().length() == 0? "" : p.getName());
            line.append(CSV_SEPARATOR);
            line.append(p.getPrice() < 0 ? "" : p.getPrice());
            line.append(CSV_SEPARATOR);
            line.append(p.getDept().toString());
            line.append("\n");
            output.write(line.toString());
        }
        output.flush();
        output.close();
    }
    catch (IOException ex)
    {
        System.out.println("IO error for " + filename +
                ": " + ex.getMessage());
    }
}

Upvotes: 0

Views: 68

Answers (2)

Aiias
Aiias

Reputation: 4748

You are re-using the same line variable with each iteration of your for loop.

Try re-initializing line at the top of your for loop like this:

...
StringBuilder line;
for (Product p: getAllProducts()) {
  line = new StringBuilder();
  line.append(p.getId() <=0 ? "" : p.getId());
  ...

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

Use this:

public void saveProductsToDisk() {

    String filename = 

"/Users/paddy/UCSC/Workspace/productDB/src/productdb/savedProducts.csv";
    BufferedWriter output = null;
    try 
    {
        output =  new BufferedWriter(new FileWriter(filename));
        StringBuilder line = null;
        for (Product p: getAllProducts())
        {
            line = new StringBuilder();
            line.append(p.getId() <=0 ? "" : p.getId());
            line.append(CSV_SEPARATOR);
            line.append(p.getName().trim().length() == 0? "" : p.getName());
            line.append(CSV_SEPARATOR);
            line.append(p.getPrice() < 0 ? "" : p.getPrice());
            line.append(CSV_SEPARATOR);
            line.append(p.getDept().toString());
            line.append("\n");
            output.write(line.toString());
        }
        output.flush();
        output.close();
    }
    catch (IOException ex)
    {
        System.out.println("IO error for " + filename +
                ": " + ex.getMessage());
    }
}

Upvotes: 1

Related Questions