OpenCSV how to extract data from specified column to list

40 Views Asked by At

I`m writing a class to parse csv file and extract data from specified column to list. but im facing java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 1 when i try to invoke this method

public class CsvDataReader {
    public static List<String> extractColumnData(String filePath, String columnName) throws IOException, CsvException {
        List<String> columnData = new ArrayList<>();
        CSVParser csvParser = new CSVParserBuilder().withSeparator(';').build();

        try (CSVReader reader = new CSVReaderBuilder(new FileReader(filePath)).withCSVParser(csvParser).build()) {
            List<String[]> allRows = reader.readAll();

            // Find the index of the desired column (case-insensitive)
            int columnIndex = -1;
            String[] headerRow = allRows.get(0);
            for (int i = 0; i < headerRow.length; i++) {
                if (headerRow[i].equalsIgnoreCase(columnName)) {
                    columnIndex = i;
                    break;
                }
            }

            if (columnIndex == -1) {
                throw new IllegalArgumentException("Column not found: " + columnName);
            }

            // Extract data from the specified column
            for (int i = 1; i < allRows.size(); i++) {
                String[] row = allRows.get(i);
                columnData.add(row[columnIndex]);
            }
        }

        return columnData;
    }
}

this is my csv

ID;NKz;sB;Name;Supplied_ID;DPID
9837;413;70;70V10;9837;A
9837;413;70;70V10;9839;A
9837;413;70;70V10;9840;A

in this example i use method like this .extractColumnData(filePath, "Supplied_ID"); filePath is specified correctly What im doing wrong?

0

There are 0 best solutions below