Home » Java » database – How to check if particular data is present in CSV file or not in java?-Exceptionshub

database – How to check if particular data is present in CSV file or not in java?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created a CSV file and put values by connecting with the database in java.

Now, I have to check if a particular data/ID is present in the CSV file or not? The CSV file contains multiple columns but I have to perform check on a single column of the CSV file.

How to&Answers:

First of all you need a way to iterate the rows of your CSV file, then get the value in the column you want, and then compare that to the value you’re searching for.

Fortunately there is an abundance of libraries that will simplify the handling of CVS files. Apache Commons has one that will read a file into an Iterable of CSVRecords. Check the docs here

A function that does what you ask for could be:

    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;
    }