Search code examples
javacsvopencsv

How to delete a specific row from a CSV file using search string


I am working on java project where I have to delete a specific row from a CSV file using java. Currently I am using opencsv. I am trying to achieve the below scenario where I have to delete the 3rd row from the list and I have two strings as input.

String 1 : cat

String 2 : mars

enter image description here

I am able to get the exact row and its number with my current code. How can I delete this row?

Here is my code:

private static void updateCsv(String string1 , String String2) throws IOException {
    try {
        CSVReader reader = new CSVReader(new FileReader(OUTPUTFILE), ',');
        List<String[]> myEntries = reader.readAll();
        reader.close();

        //Iterate through my array to find the row the user input is located on
        int i = 1;
        for (String[] line : myEntries) {
            String textLine = Arrays.toString(line).replaceAll("\\[|\\]", "");
        
            //here i am checking for the two strings
            if (textLine.contains(string1) && textLine.contains(string2) ) {
                //here i am able to get the count the row as 3
                System.out.println("Found - Your item is on row: ...:" + i);
                // how can i delete the row that i have now ?
          
            } else {
                //System.out.println("Not found");
            }
            i++;
        }
    } catch (IOException e) {
        System.out.println(e);
    }
 }

Solution

  • List<String[]> filtered = myEntries.stream()
                                       .filter(entry -> !entry[1].equals(string1) &&
                                                        !entry[2].equals(string2)
                                       .collect(Collectors.toList());
    FileWriter fw = new FileWriter("result.csv");
    CSVWriter w = new CSVWriter(fw);
    filtered.forEach(line -> w.writeNext(line));
    

    You can't delete a line from a file in java.

    In the code in your question you load the entire contents of the CSV file into a List. What you want is to write all the List entries to a file except the line that contains string1 and string2.

    According to the sample data in your question, string1 is compared with column B and string2 is compared with column C. Column B corresponds to the element at index 1 in the String array that contains a single line from the CSV file. Similarly, column C corresponds to index 2.

    Using the stream API, that was introduced in Java 8, you simply filter out the unwanted line. The resulting list contains all the lines that you want to keep, so just write them to another file. After that, if you like, you can delete the original CSV file and rename the resulting file (which I named "result.csv" in my code, above).