gpt4 book ai didi

Java writer 只写入 arraylist 的最后一个元素

转载 作者:行者123 更新时间:2023-12-02 03:59:09 25 4
gpt4 key购买 nike

这是我的问题,我有一个对象数组列表,我希望将其写入文本文件。在大多数情况下,这是可行的,但令人烦恼的是,它只写入数组列表的最后一个元素。我的代码如下:

public void write() throws IOException {
try {
File file = new File("C:\\contacts.txt");
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(contacts contact:contactList) {
StringBuffer contactrec=new StringBuffer();
contactrec.append(contacts.getID());
contactrec.append(",");
contactrec.append(contacts.getName());
contactrec.append(",");
contactrec.append(contacts.getNotes());
bw.write(contactrec.toString());
bw.newLine();
System.out.println("Contacts have been updated");
}

bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

如果数组列表的大小为 3,则编写器会将数组列表的最后一个元素写入文件 3 次。所以如果最后一个元素是:“12,John Doe,fish”文本文件将具有:

 12,John Doe,fish
12,John Doe,fish
12,John Doe,fish

写在里面。我想知道如何修复以及为什么会发生这种情况,如有任何帮助,请提前致谢。

我的联系人类是这样的,并填充了从 csv 文件读取的对象:

public class contacts {
private static String ID;
private static String Name;
private static String Notes;

public contacts(String ID, String Name, String Notes){
this.ID = ID;
this.Name = Name;
this.Notes = Notes;
}

public static String getID(){
return ID;
}

public static String getName(){
return Name;
}

public static String getNotes(){
return Notes;
}

@Override
public String toString(){
return("ID = " + this.getID() + " " + "Name = " + this.getName()+ " " + "Notes = " + this.getNotes());
}
}

最佳答案

您使用的是静态方法,因此一切都与 contacts 类相关,而不是与对象 contact 相关。

因此将数据访问器方法更改为非静态。正确填充对象,然后在 for 循环中使用 contact,而不是使用 contacts

关于Java writer 只写入 arraylist 的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092780/

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