How to append a row to an existing file?
villain-bryan opened this issue · 4 comments
Maybe I'm missing something obvious .. I want to simply add a row of data to a CSV file that already exists on disk.
Using CsvWriter and writeRow does not create a row at the bottom of the file. I noticed things changed in the version overhaul, and the CsvAppender and appendLine stuff is gone.
So, using the CsvWriter how can you open an existing CSV file and add a row of new data?
Simply use the OpenOptions of CsvWriterBuilder#build(Path, Charset, OpenOption...)
for that.
Example:
try (CsvWriter csv = CsvWriter.builder().build(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
csv.writeRow("value1", "value2");
}
Not sure how I missed that. Thank you @osiegmar
@villain-bryan @osiegmar do you have a simple piece of code that appends data in an existing csv file?
I have tried this:
try (CsvWriter csv = CsvWriter.builder().build(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
csv.writeRow("value1", "value2");
}
but this creates a csv file and overwrites everything. I am lost in how shall I append data if there's already some pre-existing data in csv. Could you help me please?
The following code:
public static void main(String[] args) throws IOException {
Path path = Paths.get("foo.csv");
try (CsvWriter csv = CsvWriter.builder().build(path, UTF_8, CREATE_NEW)) {
csv.writeRow("value1", "value2");
}
try (CsvWriter csv = CsvWriter.builder().build(path, UTF_8, APPEND)) {
csv.writeRow("value3", "value4");
}
}
creates this file foo.csv
:
value1,value2
value3,value4