gpt4 book ai didi

java - 将数组列表保存到文件中时遇到问题

转载 作者:行者123 更新时间:2023-12-02 06:59:23 26 4
gpt4 key购买 nike

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

最佳答案

使用这个:

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

关于java - 将数组列表保存到文件中时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com