首页 > 解决方案 > java - 如何检查CSV文件中是否存在特定数据?

问题描述

我创建了一个 CSV 文件并通过在 java 中连接数据库来放置值。

现在,我必须检查 CSV 文件中是否存在特定的数据/ID?CSV 文件包含多个列,但我必须对 CSV 文件的单个列执行检查。

标签: javadatabasefilecsv

解决方案


首先,您需要一种方法来迭代 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;
    }

推荐阅读