简体   繁体   中英

How do I print the next element in a linked list to a CSV file?

I'm making an address book and my program is supposed to save each element in a list to a CSV file. I've gotten everything to work asside from the fact that it will only save 1 line to the file.

public static void save(){
PrintWriter writer = null;
try {
    writer = new PrintWriter("C:\\Users\\Remixt\\workspace\\2\\AddressBook.csv", "UTF-8");
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.exit(0);
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.exit(0);
}
 {
    writer.println(AddressBook.get(getListSize()-1)+"\n");


writer.close();//saves file
}

Edit: It will only save the last element to the file. It only shows 1 thing in the file no matter how many times i add something else to the list.

the problem is here

writer.println(AddressBook.get(getListSize()-1)+"\n");

you just write the last element of AddressBook to the csv file, use for loop

the following is a sample

for (int i = 0; i < AddressBook.size(); i++) {
     writer.println(AddressBook.get(i)+"\n");

}

at last, you should write file by append mode

 filename=new FileWriter("printWriter.txt",true);
 writer=new java.io.PrintWriter(filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM