I keep getting a null pointer exception with this code:
It's suppose to load a text file into a textArea.

JFileChooser chooser = new JFileChooser();
	 int returnVal = chooser.showOpenDialog(this);
	 String getFile = chooser.getName();
	 if(returnVal == JFileChooser.APPROVE_OPTION)
		 try {
			 FileReader filegetter = new FileReader(getFile);
			 BufferedReader br = new BufferedReader(filegetter);
			 String line = br.readLine();
			 while ((line)!= null)
		 catch (FileNotFoundException ex)
		 catch (Exception myE)

and which line throws the exception?

in the: public static void main(String[] args)

I have set up everything correctly just getting this one error

not which method, which line.

If you know exactly (to the line) where the exception occurrs you will probably be enlightened as to the cause.

OK, I think I found your problem.

String getFile = chooser.getName();
String getFile = chooser.getSelectedFile().getPath();

The reason you received a Null Pointer exception is
FileReader filegetter = new FileReader(getFile);
returns the name of the file. However getFile only contains the name of the file, not where to get it (path).

So since 'new FileReader(getFile);' can't find the file it returns NULL, hence the NPE.

getFile = chooser.getSelectedFile().getPath();
returns the fully qualified file with path information.

Hope this helps! ;)

This article has been dead for over six months. Start a new discussion instead.