Reputation: 67
I am running java code using Netbeans IDE in Ubuntu 12.04.
I am trying to create a file object with a pathname to a file directory and using the method listFiles() to return an array of pathnames under this file directory.
The code:
File allFile=new File("~/Desktop/matlab/CAT_00");
File[] fileList = allFile.listFiles();
However when i ran the the code, i get an exception declaring
Exception in thread "main" java.lang.NullPointerException
at CatTest.main(CatTest.java:29)
Java Result: 1
So it appears that either my allFile object contains null object? I am not really sure myself. I tried checking the directory path that i wanted which was "~/Desktop/matlab/CAT_00" and it was correct. I tried using the debugging mode to check these 2 lines of code and found that listFiles() returned this exception error. However i do not understand why there should be an null exception error since there was files and directories under the CAT_00 main directory i created the File object with in the 1st place and hence should have returned an array of pathnames for these files and directories instead.
Help is much appreciated!!
Upvotes: 1
Views: 2502
Reputation: 2416
The reason why you're getting a NullPointerException is because when you run listFiles() the path provided is does not actually exist.
In Java you can not reference a file directly from ~/ because Java looks at file paths as if they're URLs relative to where they are run. In your case since you are running inside Eclipse, it's relative to your Eclipse workspace. Instead what you should use is
String homeDir = System.getProperty("user.home");
File allFile = new File(homeDir + "/Desktop/matlab/CAT_00");
File[] fileList = allFile.listFiles()
What System.getProperty("user.home")
will do is get the user's absolute home directory path, no matter the OS they're running.
Upvotes: 5