jrl
jrl

Reputation: 27

How to remove a row from a csv file if that row contains a certain data in java

I have a csv file that basically mimics a database and my goal is to remove a row from that csv if the csv file contains that username input I provide

the current csv file is:

   Jack chan,customer,[email protected],jack12,3144134414,13 Arboretum,user2
   Donald tusk,customer,[email protected],donald1,1213141114,14 Arboretum,user3 
   tom jack,customer,[email protected],tom44,131344122,14 wells st,user34
   jack,parking officer,[email protected],jack,12131131134,12ddcscs,peo1
   jewel khan,parking officer,[email protected],jwel12,2131412141,12 wliis str,peo2
   shane li,parking officer,[email protected],shaneli,1343513414,13 mac st,peo33
   james chang,parking officer,[email protected],james12,31452434114,13 chang st,peo77

my objective is to remove the row of say Shane li using his username "shaneli" and not causing any change to other data. but the current code I have is not causing the file's other data to change

the expected output csv file is row with shaneli gets deleted with other rows remaining intact:

   Jack chan,customer,[email protected],jack12,3144134414,13 Arboretum,user2
   Donald tusk,customer,[email protected],donald1,1213141114,14 Arboretum,user3 
   tom jack,customer,[email protected],tom44,131344122,14 wells st,user34
   jack,parking officer,[email protected],jack,12131131134,12ddcscs,peo1
   jewel khan,parking officer,[email protected],jwel12,2131412141,12 wliis str,peo2
   james chang,parking officer,[email protected],james12,31452434114,13 chang st,peo77

this is the code java code I have and I need a java solution:

private static String userPath = "/CSVs/database.csv";
    
public void removeUser(String name,String userType,String email,String userName,String phoneNumber,String address,String password) {
        
        // FIX THIS
        String tmpFile = "tmp.csv";
//      String target1 = ""; String target2 = ""; String target3 = ""; String target4 = ""; String target5 = "";String target6 = "";String target7 = "";
        String target = "";
        File oldFile = new File(userPath);
        File newFile = new File(tmpFile);
        
        System.out.println(userName);
        try {
            FileWriter fw = new FileWriter(tmpFile, true);
            BufferedWriter bfw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bfw);
            x = new Scanner(new File(userPath));
            x.useDelimiter("[,\n]");
            
            while (x.hasNext()) {
                target = x.next();
                if (!target.equals(userName)) {
                    pw.printf("%s,%s,%s,%s,%s,%s,%s\n", name, userType,email,userName,phoneNumber,address,password);
//                  pw.println(target + "," + target + "," + target + "," + target + "," + target + "," + target + "," + target);
                }
            }
            x.close();
            pw.flush();
            pw.close();
            oldFile.delete();
            File dmp = new File(userPath);
            newFile.renameTo(dmp);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

Please advice Thanks in advance !!

Upvotes: 1

Views: 764

Answers (2)

Miuccia
Miuccia

Reputation: 11

You need to delete the whole row containing specific data from a CSV file. The Java code will be rather long if you try to use the high-level language to do this. It is very simple to accomplish the task in SPL, an open-source Java package. You just need one line of code, as shown below:

A
1 >file("tmp.csv").export@c(file("database.csv").import@wc().select(~(4)!=userNameToDelete))

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as removeUser.splx and invoke it in Java in the same way you call a stored procedure:

…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call removeUser(?)");
st.setObject(1,"shaneli");
st.execute();
…

Upvotes: 0

user8821675
user8821675

Reputation:

Solution

The way I've come up with is to do the following:

  1. Create a new file
  2. If the username is not equal, add line, otherwise skip it

Just as we've listed out our steps, we can create a function to do each one.

Code

1) Creating a new file

private void createFile(){
    try {
        File myObj = new File("CSVs/tmpFile.csv");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

We can then create the file which will be stored at the desired file path and stored as tmpFile.csv.

2) If the username are not equal, add line

private void addDataContents(String userNameToDelete){
    try{
        String userPath = "CSVs/database.csv";
        BufferedReader csvReader = new BufferedReader(new FileReader("CSVs/database.csv"));
        String row;
        FileWriter myWriter = new FileWriter("CSVs/tmpFile.csv");

        while (((row = csvReader.readLine()) != null)){
            String[] line = row.split(",");
            if (!line[3].equals(userNameToDelete)){
                myWriter.write(row + "\n");
            }
        }
        myWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

We then read through the contents of database.csv. We read every line one by one and split the line up by commas as it is a CSV file ( Comma Separated Values ). As the username will always be stored in the 3rd index, we can compare the username we wish to delete with the value stored at the index. If they are not the same, we can go ahead and write the line to our new file. If they are the same, our loop will just continue onto the next line.

Final Notes

I hope everything is easy to read and understandable.

Upvotes: 2

Related Questions