/** * List all files/directories in a directory * * @param directory Directory to list files in * @param recursive If the search should be done recursively * @param includeFiles If files should be included in the list * @param includeDirs If directories should be included in the list * @return List of files/directories * @throws IOException If an error listing the file occurs */ public static Set<String> listAllFilesNames(File directory, boolean recursive, boolean includeFiles, boolean includeDirs) throws IOException { HashSet<String> filepaths = new HashSet<String>(); recursiveFileNameList(filepaths, directory, null, recursive, includeFiles, includeDirs); return filepaths; }
/** * List all files/directories in a directory * * @param directory Directory to list files in * @param recursive If the search should be done recursively * @param includeFiles If files should be included in the list * @param includeDirs If directories should be included in the list * @return List of files/directories * @throws IOException If an error listing the file occurs */ public static Set<String> listAllFilesNames(File directory, boolean recursive, boolean includeFiles, boolean includeDirs) throws IOException { HashSet<String> filepaths = new HashSet<String>(); recursiveFileNameList(filepaths, directory, null, recursive, includeFiles, includeDirs); return filepaths; }
private static void recursiveFileNameList(HashSet<String> filepaths, File file, String path, boolean recursive, boolean includeFiles, boolean includeDirs) throws IOException { if (file.isDirectory()) { if (path == null || recursive) { File[] files = file.listFiles(); if (files == null) { throw new IOException("Unable to list files in directory: " + file.getPath()); } for (File f : files) { recursiveFileNameList(filepaths, f, path != null ? path + File.separator + f.getName() : f.getName(), recursive, includeFiles, includeDirs); } } if (path != null && includeDirs) { filepaths.add(path); } } else { if (includeFiles) { filepaths.add(path); } } }
private static void recursiveFileNameList(HashSet<String> filepaths, File file, String path, boolean recursive, boolean includeFiles, boolean includeDirs) throws IOException { if (file.isDirectory()) { if (path == null || recursive) { File[] files = file.listFiles(); if (files == null) { throw new IOException("Unable to list files in directory: " + file.getPath()); } for (File f : files) { recursiveFileNameList(filepaths, f, path != null ? path + File.separator + f.getName() : f.getName(), recursive, includeFiles, includeDirs); } } if (path != null && includeDirs) { filepaths.add(path); } } else { if (includeFiles) { filepaths.add(path); } } }