0

given is an existing CSV file with the following example structure/content:

id,password,role
user1,1234,student
user2,1234,professor

I want to create a basic DAO with simple CRUD operations in Java to access and modify that data. Is it possible to update/edit a single record/line? Or do I have to completely parse and rewrite the file?

Current implementation:

package com.testproject.persistence;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.testproject.model.User;

public class UserDAO {
    private final static String CSV_FILE = "/Users/someuser/Desktop/test.csv";

    /**
     * 
     * @param user
     */
    public void add(User user) {
        try {
            FileWriter writer = new FileWriter(CSV_FILE, true);

            writer.append(user.getId());
            writer.append(';');
            writer.append(user.getPassword());
            writer.append('\n');

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @param user
     */
    public void update(User user) {
        //
    }

    /**
     * 
     * @param userId
     */
    public void delete(String userId) {
        //
    }

    /**
     * 
     * @return
     */
    public List<User> findAll() {
        return null;
    }

    /**
     * 
     * @param userId
     * @return
     */
    public User findByPrimaryKey(String userId) {
        return null;
    }
}

Thanks and kind regards

Philipp

  • i think u will get some help form this question [this question asked here](http://stackoverflow.com/questions/822150/modify-a-txt-file-in-java) – Madhusudan Joshi May 02 '13 at 11:16

1 Answers1

0

The approach: Read original csv -> Change the content in memory and write to a new file-> Delete the old file -> Rename the new file)

Two approaches to achieve this:

FIRST: If your csv is not too big 1. Create an object representing each line of the csv 2. Represent the csv as collection of objects after reading the csv

CREATE: Add an object in your collection and re-write the file

READ : Simple read from the collection as your collection is a replica of your csv

UPDATE: Update the object in your collection and re-write the csv

DELETE : Delete the object from the collection and re-write the csv

**The benefit of this approach is READS are free from file read.

SECOND: If your csv is too big and you have memory constraints, then avoiding creating the collection but still you will have to re-write the file as you do any update to it.

** The benefit of this approach is that you save memory but your READS are also slow

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136