【问题标题】:Trouble saving arraylist into a file无法将arraylist保存到文件中
【发布时间】:2013-06-01 05:38:34
【问题描述】:

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

1,ipad,499.0,电子 2,Java电子书,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());
    }
}

【问题讨论】:

  • 一个有用的练习是,当您遇到此类错误时,在脑海中仔细检查您的代码,以了解它在每一步中所做的事情。这样做,错误就很明显了。
  • 我会记住的.. 你们让每个人都成为更好的程序员:)

标签: java arraylist bufferedwriter


【解决方案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());
    }
}

【讨论】:

  • @HovercraftFullOfEels 我只是纠正了用户的问题。但我接受你的评论并更新它:-)
  • 太棒了..我明白了..非常感谢!!
  • @Paddy 您可以接受答案,以便其他人受益:-)
【解决方案2】:

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

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

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

【讨论】:

  • @HovercraftFullOfEels - 我将更改我的答案以使用StringBuilder 而不是StringBuffer。如果 line 正在其他地方使用,我正在尝试修复错误,而不会破坏 OP 的其他代码。
猜你喜欢
  • 1970-01-01
  • 2015-04-30
  • 2016-10-28
  • 1970-01-01
  • 2014-05-11
  • 2017-03-25
  • 2012-07-23
  • 1970-01-01
  • 2012-12-04
相关资源
最近更新 更多