如何使用搜索字符串从 CSV 文件中删除特定行

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

我正在处理 java 项目,我必须使用 java 从 CSV 文件中删除特定行。目前我正在使用 opencsv。我正在尝试实现以下场景,我必须从列表中删除第 3 行并且我有两个字符串作为输入。

字符串 1:猫

字符串 2:火星

我可以用我当前的代码得到准确的行和它的编号。我怎样才能删除这一行?

这是我的代码:

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);
    }
 }
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));

您不能从 java 中的文件中删除一行。

在您问题的代码中,您将 CSV 文件的全部内容加载到 List。您想要的是将所有 List 条目写入文件 除了 包含 string1string2.

的行

根据您问题中的示例数据,string1 与列 B 进行比较,string2 与列 C 进行比较。列 B 对应于 String 数组中索引 1 处的元素,该数组包含 CSV 文件中的一行。同样,列 C 对应于索引 2.

使用 Java 8 中引入的流 API,您只需过滤掉不需要的行。结果列表包含您要保留的所有行,因此只需将它们写入另一个文件即可。之后,如果您愿意,可以删除原始 CSV 文件并重命名生成的文件(我在上面的代码中将其命名为“result.csv”)。