Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to the last line of CSV file in Java

Tags:

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();     } 
like image 453
AreYouSure Avatar asked Nov 24 '11 11:11

AreYouSure


People also ask

How do I append a CSV file in Java?

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.

How do you go to the next line in a CSV file in Java?

You just have to change csvWriter. print("world"); to csvWriter. println("world"); . The next print going to be in next new line.

How do I append a CSV file to a list?

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.


2 Answers

Try opening file like this

FileWriter pw = new FileWriter("F:\\data.csv",true);  

Pass true argument for appending.

like image 199
gprathour Avatar answered Sep 24 '22 11:09

gprathour


use FileWriter pw = new FileWriter("F:\\data.csv", true);

reference: FileWriter

like image 43
yas4891 Avatar answered Sep 25 '22 11:09

yas4891