I am working in java project and i am using apache metamodel to insert data into csv file.
Code:
public void insertIntoCSVFile(){
File myFile = new File("unexisting_file.csv");
UpdateableDataContext dataContext = DataContextFactory.createCsvDataContext(myFile);
final Schema schema = dataContext.getDefaultSchema();
dataContext.executeUpdate(new UpdateScript() {
public void run(UpdateCallback callback) {
// CREATING A TABLE
Table table = callback.createTable(schema, "my_table")
.withColumn("name").ofType(VARCHAR)
.withColumn("gender").ofType(CHAR)
.withColumn("age").ofType(INTEGER)
.execute();
// INSERTING SOME ROWS
callback.insertInto(table).value("name","John Doe").value("gender",'M').value("age",42).execute();
callback.insertInto(table).value("name","Jane Doe").value("gender",'F').value("age",42).execute();
}
});
}
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?
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:
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:
For further info, see the semantics for the creation of tables in CSV files - specifically:
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:
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:
Using the above approach, here is a full example:
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.