[英]Trouble saving arraylist into a file
我有以下代碼,我從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());
}
}
您在for
循環的每次迭代中重復使用相同的line
變量。
嘗試重新初始化for
循環頂部的line
,如下所示:
...
StringBuilder line;
for (Product p: getAllProducts()) {
line = new StringBuilder();
line.append(p.getId() <=0 ? "" : p.getId());
...
用這個:
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.