0

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)
			 {
			 textArea2.setText(line);
			 }
		 }
		 catch (FileNotFoundException ex)
		 {
			 ex.printStackTrace();
		 }
		 catch (Exception myE)
		 {
			 myE.printStackTrace();
		 }
	 }
3
Contributors
5
Replies
6
Views
13 Years
Discussion Span
Last Post by server_crash
0

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

0

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.

0

OK, I think I found your problem.

Change
String getFile = chooser.getName();
to
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.

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

Hope this helps! ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.