Question

I am writing a utility method for parsing csv files. For some reason, this method is showing a null pointer exception during insertion into a list of maps. I am not sure why. Can someone run your eyes on this and explain why this could be happening? This is the point of the nullpointer exception:

record.put(header[i].toString(), nextLine[i].toString());

Here is the file to parse:

id;state;city;total_pop;avg_temp
1;Florida;Miami;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;190000;34

And the code:

public class FileParserUtil {


    public List<Map<String, String>> parseFile(String fileName, char seperator)
            throws IOException {

        CSVReader reader = new CSVReader(new FileReader(fileName), seperator);
        Map<String, String> record = null;
        List<Map<String, String>> rows = null;

        // int colcnt = reader.readNext().length;
        String[] header = reader.readNext();
        String[] nextLine;

        while ((nextLine = reader.readNext()) != null) {

            for (int i = 0; i< nextLine.length; i++){

                System.out.println(header[0]);
                System.out.println(nextLine[0]);

                System.out.println(header[1]);
                System.out.println(nextLine[1]);

                System.out.println(nextLine.length);

                 record.put(header[i].toString(), nextLine[i].toString());

            }
            rows.add(record);
        }
        reader.close();
         return rows;

    }
}
Was it helpful?

Solution

You variable header[i] probably does not have the same length of nextLine[i], so you cannot use the same index i to retrieve its elements.

Edit: I think you forgot to initialize Map<String, String> record. Is that it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top