Java – Recursive method to search through folder tree and find specific file types

directoryjavarecursionsubdirectory

So I am writing a code that locates certain information on Protein databases. I know that a recursive folder search is the best possible way to locate these files, but I am very new to this language and have been told to write in Java (I normally do C++)

SO this being said, what method would i use to:

First: Locate the folder on desktop
Second: Open each folder and that folders subfolders
Third: Locate files that end with the ".dat" type (because these are the only files that have stored the Protein information

Thanks for any and all help you can provide

Best Answer

  1. java.io.File is "An abstract representation of file and directory pathnames"
  2. File.listFiles provides a listing of all the files contained within the directory (if the File object represents a directory)
  3. File.listFiles(FileFilter) provides you with the ability to filter a file list based on your needs

So, with that information...

You would specify a path location with something like...

File parent = new File("C:/path/to/where/you/want");

You can check that the File is a directory with...

if (parent.isDirectory()) {
    // Take action of the directory
}

You can list the contents of the directory by...

File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...

You can filter the list in a similar way...

File[] children = parent.listFiles(new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory() || file.getName().toLowerCase().endsWith(".dat");
        }
    });
// This will return all the files that are directories or whose file name ends
// with ".dat" (*.dat)

Other useful methods would include (but not limited to)

Related Topic