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

Date: 2019jun10 Update: 2025sep30 Language: Java Q. Java: Best way to use File.listFiles() and File.list() A. These member functions can return null which might make your application crash so I always check for null and assign an empty array when that occurs. As shown in this full example:
import java.io.File; class Demo { static File[] getDirFiles(final File dir) { File list[] = dir.listFiles(); if (list == null) list = new File[]{}; return list; } static String[] getDirNames(final File dir) { String[] list = dir.list(); if (list == null) list = new String[]{}; return list; } public static final void main(String []args) { { var strDir = "/etc"; // Folder exists var names = getDirNames(new File(strDir)); System.out.println(strDir + " has " + names.length + " files"); } { var strDir = "/junk"; // Folder does not exist, but we don't crash var names = getDirNames(new File(strDir)); System.out.println(strDir + " has " + names.length + " files"); } } }
Output:
/etc has 321 files /junk has 0 files