1

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!!

7
  • 1
    For better help sooner, post an SSCCE. Commented Jan 11, 2013 at 4:14
  • BTW - change File allFile=new File("~/Desktop/matlab/CAT_00"); .. to immediately print out allFile.exists() & allFile.isDirectory(). Commented Jan 11, 2013 at 4:21
  • @AndrewThompson, i'm sorry but what does SSCCE mean? Thanks i try that and post the results Commented Jan 11, 2013 at 4:23
  • @BhavikShah, yes it is a directory that contains files and directory Commented Jan 11, 2013 at 4:23
  • 1
    similar posts which may be of help NullPointerException when using java.io.File & Exception java.lang.NullPointerException Commented Jan 11, 2013 at 5:51

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks nhydock and Andrew! The help both of you provided helped me moved on! =))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.