Search code examples
javafilefile-iodirectory-structure

how to get name of all file in a directory and sub-directory in java


I have a directory which consist of some different sub directory which every one have several files. how can i get name of all file?


Solution

  • If you want to use a library, try the listFiles method from apache commons io FileUtils, which will recurse into directories for you.

    Here's an example of how you could call it to find all files named *.dat and *.txt in any directory anywhere under the specified starting directory:

    Collection<File> files = FileUtils.listFiles(new File("my/dir/path"), {"dat", "txt"}, true);