无法将arraylist保存到文件中

时间:2013-06-01 05:38:34

标签: java arraylist bufferedwriter

我有以下代码,我从main调用。 代码的麻烦,它节省了产品 如下: 1,ipad公司,499.0,ELECTRONICS

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

我不明白第一个来自哪里。 能否请你提供一些指示。

非常感谢...

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

2 个答案:

答案 0 :(得分:1)

您在line循环的每次迭代中重复使用相同的for变量。

尝试重新初始化line循环顶部的for,如下所示:

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

答案 1 :(得分:1)

使用此:

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