How to read the specific data from csv file in Java in open csv

62 Views Asked by At

I am having csv file like below

AccountNumber,reason
1234567890,add 2345678901,dfg

I wrote a code as below for printing all the data from csv file

public CSV(){ 

public static void main(String[]     args){

CSVReader csvreader = new     CSVReader ( new FileReader(file     name);

List<String> lines =     csvreader.readAll();

for(String[] line:lines){

   for(int i=0; i<line.length; i        ++){
   Sop(line[i]);
 }
 Sop(“/n”);
}
}
}

My requirement is to print the last 6 digits of the first column in csv file

Account number 567890 678901

Can anyone please help me

1

There are 1 best solutions below

2
Marco Riccetti On

You can do something like this:

public static void readDataFromCustomSeparator(String file) {
    try {
        // Create object of filereader
        // class with CSV file as a parameter.
        FileReader fileReader = new FileReader(file);

        // Create CSVParser object with
        // custom separator semi-colon
        CSVParser parser = new CSVParserBuilder().withSeparator(',').build();

        // Create CSVReader object with
        // parameters fileReader and parser
        CSVReader csvReader = new CSVReaderBuilder(fileReader)
                .withCSVParser(parser)                           
                .withSkipLines(1) 
                .build();

        // Read all data at once
        List<String[]> allData = csvReader.readAll();

        // Process Data
        for (String[] row : allData) {
            // Ensure that the row has at least one element
            if (row.length > 0) {
                // Get the first column
                String firstColumn = row[0];

                // Get the last six digits of the first column
                String lastSixDigits = firstColumn.length() >= 6
                        ? firstColumn.substring(firstColumn.length() - 6)
                        : firstColumn;

                // Print or use the last six digits
                System.out.println(lastSixDigits);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This code snippet reads data from a CSV file using the OpenCSV library, with a focus on custom separators and processing only the first column. The snippet provided below has been modified based on the guide available at https://www.geeksforgeeks.org/reading-csv-file-java-using-opencsv/. For more examples and explanations, please refer to the original guide.

Note:

For large files, it is recommended to use an approach similar to the following:

public static void readDataFromCustomSeparator(String file) {
    try {
        // Create object of filereader
        // class with CSV file as a parameter.
        FileReader fileReader = new FileReader(file);

        // Create CSVParser object with
        // custom separator semi-colon
        CSVParser parser = new CSVParserBuilder().withSeparator(',').build();

        // Create CSVReader object with
        // parameters fileReader and parser
        CSVReader csvReader = new CSVReaderBuilder(fileReader)
                .withCSVParser(parser)
                .withSkipLines(1) 
                .build();

        // Process Data
        String[] nextRecord;
        while ((nextRecord = csvReader.readNext()) != null) {
            // Ensure that the record has at least one element
            if (nextRecord.length > 0) {
                // Get the first column
                String firstColumn = nextRecord[0];

                // Get the last six digits of the first column
                String lastSixDigits = firstColumn.length() >= 6
                        ? firstColumn.substring(firstColumn.length() - 6)
                        : firstColumn;

                // Print or use the last six digits
                System.out.println(lastSixDigits);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

To respond to your comment, you can check this version that first reads the header row to identify the column names and then searches for the "AccountNumber" column by comparing names. If found, it processes the data in that column.

public static void readDataFromCustomSeparator(String file) {
    try {
        // Create object of filereader
        // class with CSV file as a parameter.
        FileReader fileReader = new FileReader(file);

        // Create CSVParser object with
        // custom separator semi-colon
        CSVParser parser = new CSVParserBuilder().withSeparator(',').build();

        // Create CSVReader object with
        // parameters fileReader and parser
        CSVReader csvReader = new CSVReaderBuilder(fileReader)
                .withCSVParser(parser)
                .build();

        // Process Data
        String[] nextRecord;

        // Index for the column named "AccountNumber"
        int accountNumberColumnIndex = -1;

        // Read the header row to identify the column names
        String[] header = csvReader.readNext();

        // Identify the index of the "AccountNumber" column
        for (int i = 0; i < header.length; i++) {
            if ("AccountNumber".equalsIgnoreCase(header[i])) {
                accountNumberColumnIndex = i;
                break;
            }
        }

        if (accountNumberColumnIndex == -1) {
            // Handle the case where "AccountNumber" column is not found
            System.out.println("Column 'AccountNumber' not found.");
            return;
        }

        // Continue processing the data, assuming the "AccountNumber" column is found
        while ((nextRecord = csvReader.readNext()) != null) {
            // Access the account number column using the identified index
            String accountNumber = nextRecord[accountNumberColumnIndex];

                // Get the last six digits of the account column
                String lastSixDigits = accountNumber.length() >= 6
                        ? accountNumber.substring(accountNumber.length() - 6)
                        : accountNumber;

                // Print or use the last six digits
                System.out.println(lastSixDigits);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}