0

I have the following java code to read a CSV file and store the values in an ArrayList().

        try {
        File file =new File("Data.csv");
        BufferedReader br=new BufferedReader(new FileReader(file));
        while(br.readLine() != null){
            String input=br.readLine();
            input=input.replace('"', '\0');
            datam.add(input.split(",|\\s|;"));
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("Exception");
        e.printStackTrace();
    }

But i am getting the exception at the following lines

String input=br.readLine();
            input=input.replace('"', '\0');
            datam.add(input.split(",|\\s|;"));

I am finding no error in the code. I am using the Arraylist for populating a JTable. The exception message is the following:

java.lang.NullPointerException
at com.cs319.MyTable.<init>(Lab2Swing.java:366)
at com.cs319.Lab2Swing.createPanel3(Lab2Swing.java:190)
at com.cs319.Lab2Swing.<init>(Lab2Swing.java:103)
at com.cs319.Lab2Swing$1.run(Lab2Swing.java:75)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). Hard code some CSV data to replace the file. – Andrew Thompson Jan 30 '15 at 20:59
  • Unless you have some pressing need to reinvent the wheel, I'd suggest using a presi sting library like opencsv – MadProgrammer Jan 30 '15 at 21:11

1 Answers1

4

You are callig the readLine() method twice: once in the if clause without using the return value, and then in the body of the if block, without checking whether it is null. Use a variable to store the result of readLine(), check whether this variable is null, and then access it.

Robin Krahl
  • 5,268
  • 19
  • 32