Skip to content
Advertisement

how to insert data into csv file using apche meta model?

I am working in java project and i am using apache metamodel to insert data into csv file.

Code:

JavaScript

Whenever i call this method for same csv file it inserts data successfully but deleting old data and then inserting new data so every time only two row insert.

I want to insert multiple duplicate row by calling function multiple times means new rows should append and old rows remains same.

How can i achieve this?

Advertisement

Answer

Move the table creation code outside of the data insertion method. Every time you create the table, in the CSV file, it overwrites the previous table and its contents.

Here is one approach:

JavaScript

In this example, the main method is responsible for creating the table. This method then calls the data insertion method twice, passing in the relevant context and table name.

The resulting file contents are:

JavaScript

For further info, see the semantics for the creation of tables in CSV files – specifically:

Create or overwrite the CSV file with a (new) table structure.

Update

You can prevent the data being overwritten by checking if the table already exists, before trying to create it (again).

Here is a simple example showing that approach:

First, change the table name so it matches the file name:

JavaScript

This is because MetaModel uses this as the default table name for tables in CSV files. We can use this to check if we have already created the table:

JavaScript

Using the above approach, here is a full example:

JavaScript

Now, you will only create the table in your CSV file if it does not already exist. And if it does exist, then your additional data will be appended to any data which is already in the file.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement