java - 如何使用搜索字符串从 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);
}
}
解决方案
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
条目写入文件,但包含和的行除外。string1
string2
根据您问题中的示例数据,string1
与 column 进行比较并与 columnB
进行string2
比较C
。列B
对应于String
数组中索引 1 处的元素,该元素包含 CSV 文件中的单行。同样,列C
对应于索引 2。
使用 Java 8 中引入的流 API,您只需过滤掉不需要的行。结果列表包含您要保留的所有行,因此只需将它们写入另一个文件。之后,如果您愿意,可以删除原始 CSV 文件并重命名生成的文件(我在上面的代码中将其命名为“result.csv”)。
推荐阅读
- c# - 在asp.net核心的每个请求中将用户数据存储在会话存储中还是从数据库中检索?
- forms - PowerShell复选框控制按钮功能
- c++ - 从彩色图像中去除阴影
- swift - SwiftUI:ObservedObject/ObservableObject 奇怪的行为
- windows - 无法从 Windows 10 上的主机访问 vagrant box
- php - MySQL Workbench 错误:在“读取初始通信数据包”时丢失与 MySQL 服务器的连接,系统错误:0
- python - 更新多个文件 python-gitlab
- png - PNG文件的大小是如何确定的?
- php - 如何使用教义查询生成器编写嵌套的 select sql 查询?
- node.js - 获取缺少必需参数:范围 Passport.js,快递