[英]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.我正在处理 java 项目,我必须使用 java 从 CSV 文件中删除特定行。 Currently I am using opencsv.目前我正在使用 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.我正在尝试实现以下场景,我必须从列表中删除第 3 行,并且我有两个字符串作为输入。
String 1 : cat字符串1:猫
String 2 : mars字符串2:火星
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);
}
}
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.你不能从java中的文件中删除一行。
In the code in your question you load the entire contents of the CSV file into a List
.在您问题中的代码中,您将 CSV 文件的全部内容加载到List
。 What you want is to write all the List
entries to a file except the line that contains string1
and string2
.您想要的是将所有List
条目写入文件,但包含string1
和string2
的行除外。
According to the sample data in your question, string1
is compared with column B
and string2
is compared with column C
.根据您问题中的示例数据,将string1
与列B
进行比较,将string2
与列C
进行比较。 Column B
corresponds to the element at index 1 in the String
array that contains a single line from the CSV file.列B
对应于包含来自 CSV 文件的一行的String
数组中索引 1 处的元素。 Similarly, column C
corresponds to index 2.类似地, C
列对应于索引 2。
Using the stream API, that was introduced in Java 8, you simply filter out the unwanted line.使用 Java 8 中引入的流 API,您只需过滤掉不需要的行。 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).之后,如果您愿意,您可以删除原始 CSV 文件并重命名生成的文件(我在上面的代码中将其命名为“result.csv”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.