Browse - Programming Tips - Java: best way to use File.listFiles() and File.list()

Date: 2019jun10
Language: Java

Q.	Java: best way to use File.listFiles() and File.list()

A.  But these member functions can turn null which might make your application crash
so I always check for null and assign an empty array when that occurs.
Like this:

File list[] = dir.listFiles(); if (list == null) list = new File[]{};
String[] list = dir.list(); if (list == null) list = new String[]{};
Example use:
int countDir(File dir) { String[] list = dir.list(); if (list == null) list = new String[]{}; return list.length; }