Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - Recursive method to search through folder tree and find specific file types

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...