I'm using this method for writing data into csv but the problem is that it is rewriting data again below the old data. How can I prevent it from doing this ? I tried to set the FileWriter writer = new FileWriter(answerFile, false);
but then its only writing the last array in the csv file.
I have this code:
public static void writeCsv(List<String> myList) throws IOException {
FileWriter writer = new FileWriter(answerFile, true);
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
List<String[]> myListSplitted = myList.stream().map(row -> row.split(",")).collect(Collectors.toList());
csvPrinter.printRecords(myListSplitted);
csvPrinter.flush();
csvPrinter.close();
}
This the method in which I'm calling this method:
public static void appendAnswers() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(questionFile))) {
String csvRow;
int counter = 0;
String[] csvArr;
String data;
br.readLine();
List<String> myList = new ArrayList<>();
while ((csvRow = br.readLine()) != null) {
csvArr = csvRow.split(",");
csvArr = Arrays.copyOf(csvArr, csvArr.length + 1);
csvArr[csvArr.length - 1] = answers.get(counter);
data = Arrays.toString(csvArr).replace("[", "").replace("]",
"").trim();
counter++;
myList = new ArrayList<String>(Arrays.asList(data.split("\n")));
}
writeCsv(myList);
}
From the manual page :
Prints values in a CSV format.
Values can be appended to the output by calling the print(Object) method.
Basically, CSVPrinter
emulates a printer. A printer appends new lines to whatever has already been printed.
If you want to overwrite, use FileWriter
more directly rather than a printer emulator.
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.