首页 > 解决方案 > 如何使用搜索字符串从 CSV 文件中删除特定行

问题描述

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

字符串 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);
    }
 }

标签: javacsvopencsv

解决方案


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与 column 进行比较并与 columnB进行string2比较C。列B对应于String数组中索引 1 处的元素,该元素包含 CSV 文件中的单行。同样,列C对应于索引 2。

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


推荐阅读