[英]Trouble saving arraylist into a file
I have the following code that I call from main. 我有以下代码,我从main调用。 The trouble with the code, it saves the products as follows: 1,ipad,499.0,ELECTRONICS
代码有问题,它将产品保存如下:1,ipad,499.0,ELECTRONICS
1,ipad,499.0,ELECTRONICS 2,Java Ebook,19.99,BOOK 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());
}
}
You are re-using the same line
variable with each iteration of your for
loop. 您在
for
循环的每次迭代中重复使用相同的line
变量。
Try re-initializing line
at the top of your for
loop like this: 尝试重新初始化
for
循环顶部的line
,如下所示:
...
StringBuilder line;
for (Product p: getAllProducts()) {
line = new StringBuilder();
line.append(p.getId() <=0 ? "" : p.getId());
...
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.