osiegmar / FastCSV

CSV library for Java that is fast, RFC-compliant and dependency-free.
https://fastcsv.org/
MIT License
542 stars 93 forks source link

How to append a row to an existing file? #56

Closed villain-bryan closed 3 years ago

villain-bryan commented 3 years ago

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?

osiegmar commented 3 years ago

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");
}
villain-bryan commented 3 years ago

Not sure how I missed that. Thank you @osiegmar

smriti1313 commented 2 years ago

@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?

osiegmar commented 2 years ago

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