java - java - 如何检查CSV文件中是否存在特定数据?
问题描述
我创建了一个 CSV 文件并通过在 java 中连接数据库来放置值。
现在,我必须检查 CSV 文件中是否存在特定的数据/ID?CSV 文件包含多个列,但我必须对 CSV 文件的单个列执行检查。
解决方案
首先,您需要一种方法来迭代 CSV 文件的行,然后获取所需列中的值,然后将其与您正在搜索的值进行比较。
幸运的是,有大量的库可以简化 CVS 文件的处理。Apache Commons 有一个可以将文件读取到 CSVRecords 的 Iterable 中。在此处查看文档
执行您要求的功能可能是:
public boolean columnContainsValue(String pathToFile, int columnIndex, String targetValue) throws IOException {
Reader in = new FileReader(pathToFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for (CSVRecord record : records) {
String rowValue = record.get(columnIndex);
if (targetValue.equals(rowValue) )
return true;
}
return false;
}
推荐阅读
- css - css 范围标签样式对 reactjs 中的外部范围有副作用
- ruby-on-rails - 如何仅为管理员更改重定向?通过在 Rails 上使用设计和 ActiveAdmin
- sql - 选择作为过滤器的 SQL 更新表
- kubernetes - 手动将 pod 移动到另一个 kuberntes
- python - FileNotFoundError:[Errno 2] 任务尝试保存文件时没有这样的文件或目录
- javascript - React JS - 映射函数 - 访问局部变量
- flutter - 如何从显示所有已安装应用程序的使用统计信息的列表中删除包名称?
- python - 尝试编写单行列表理解时出现缩进预期错误:if-else 变体
- git - 如何将目录更改为 Jenkins 中的克隆仓库?
- reactjs - React Redux REST API - 何时将数据重新加载到应用程序中