-5

I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.

private ArrayList<File> getFiles(String path) {

    File f = new File(path);
    ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));

    return files;
}

thanks for your help

mgrantnz
  • 375
  • 1
  • 4
  • 15
  • 1
    please post full stack trace, nullpointer at which line? – Sabir Khan Apr 26 '16 at 03:24
  • sorry, exception on this line: `ArrayList files = new ArrayList<>(Arrays.asList(f.listFiles()));` thanks – mgrantnz Apr 26 '16 at 03:25
  • 1
    Possibly because `f` is a path that refers to a non-directory on the file system, so `f.listFiles()` returns `null` – Nayuki Apr 26 '16 at 03:25
  • @dnault - its not a dupe, this post has a specific question, not generic. @Nayuki - should `path.listFiles()` not list all the files in that directory? – mgrantnz Apr 26 '16 at 03:30
  • 1
    Read [the Javadoc for File.listFiles](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles\(\)) and you'll see that it "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs." – dnault Apr 26 '16 at 03:34
  • I see. So what would be the easiest way to achieve what I'm trying to do? – mgrantnz Apr 26 '16 at 03:38
  • 1
    Check that the path name is correct first or at least check `f` for null before trying to call a method on it. – Hovercraft Full Of Eels Apr 26 '16 at 03:38

2 Answers2

1

This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist). In such cases it is always advisable to add some null checks(protective code) in your method. eg: if( f != null) { //get the list of files }

  • Thanks, I understand why the error is occurring. I have added a null check: `private List getFiles(String path) { File f = new File(path); if(f != null) { ArrayList files = new ArrayList<>(Arrays.asList(f.listFiles())); }else{ ArrayList files = new ArrayList<>(); } return files; }` but the error is still happening, therefore f is not null. – mgrantnz Apr 26 '16 at 03:41
  • Are you sure the path you provided is a directory ? See this https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(). May be adding a f.isDirectory() may help : if(f != null && f.isDirectory())) { //get list } – Ankit Malpani Apr 26 '16 at 15:27
0

may be casue by f.listFiles() return one null array.you can watch the variables in debug model

richard
  • 1
  • 2