0

I'm getting a NullPointerException error when trying to run my program at this part:

File folder = new File("mypictures");
File[] pictures = folder.listFiles();
allCards = new Card[pictures.length];

for(int i=0; i < (pictures.length); i++){
    allCards[i] = new Card(new ImageIcon(pictures[i].getPath())); 
}

It complains on the follow line:

Card[] allCards = new Card[pictures.length];
4
  • 9
    listFiles() can return null. "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs." Commented Feb 11, 2014 at 20:39
  • 1
    A NullPointerException occurs at runtime, not when compiling. Commented Feb 11, 2014 at 20:39
  • 1
    @ZouZou write that up as an answer! Commented Feb 11, 2014 at 20:39
  • @PeterBratton This is just the doc after all ! :) Commented Feb 11, 2014 at 20:41

2 Answers 2

5

If folder does not refer to a directory, listFiles() will return null. I.e., when you attempt to call pictures.length, you'll fail with a NullPointerException.

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

Comments

0

Quite a few things can go wrong in your code. Please use try catch and make sure that folder exists before listing files in the folder.

Comments

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.