The code below is what I currently have, however it overwrites any data in the csv file at that time, instead of appending it to the end. Is there an easy way to do this?
public void printCustomerList() throws IOException{ FileWriter pw = new FileWriter("F:\\data.csv"); Iterator s = customerIterator(); if (s.hasNext()==false){ System.out.println("Empty"); } while(s.hasNext()){ Customer current = (Customer) s.next(); System.out.println(current.toString()+"\n"); pw.append(current.getName()); pw.append(","); pw.append(current.getAddress()); pw.append("\n"); } pw.flush(); pw.close(); }
To append/add something to an existing file, simply specify the second parameter to be true as following: FileWriter fstream = new FileWriter(loc, true); FileWriter fstream = new FileWriter(loc, true); This will keep adding content to the existing file instead of creating a new version.
You just have to change csvWriter. print("world"); to csvWriter. println("world"); . The next print going to be in next new line.
Append Data in List to CSV File in Python Using writer. writerow() In this case, before we append the new row into the old CSV file, we need to assign the row values to a list. Next, pass this data from the List as an argument to the CSV writer() object's writerow() function.
Try opening file like this
FileWriter pw = new FileWriter("F:\\data.csv",true);
Pass true
argument for appending.
use FileWriter pw = new FileWriter("F:\\data.csv", true);
reference: FileWriter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With