getting a nullpointer exception
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();
}
}
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
and which line throws the exception?
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
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
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
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.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
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! ;)
jerbo
Junior Poster in Training
84 posts since Sep 2004
Reputation Points: 11
Solved Threads: 1
Thanks jerbo, that worked perfectly!
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20