Search code examples
javaalgorithmfile-search

Most efficient way to find total files of certain format that exist in the directory


In my android app I need to find if a file of a certain format exists in the directory. I wrote the code and it works well but if the directory has too many directories each of which has many files and directories it becomes a bit slow.

Note: I am also calculating total txt files in the directory

This is my code

int count = 0;

private boolean containsTXT(File file) {
        boolean result = false;
        String fList[] = file.list();

        if (fList == null)
            return false;
        else {
            for (int i = 0; i < fList.length; i++) {
                File file = new File(file, fList[i]);
                if (file.isFile() && (file.getName().endsWith("txt"))) {
                    result = true;
                    count++;   // This counts total txt files in the dir
                } else if (file.isDirectory()) {
                    result = containsTXT(file);
                }
            }
        }
        return result;
    }

I am basically following the most general approach but there are apps which do the same job that i am trying to do in my app and are faster. Does anybody know of a better approach or algorithm for this task? Thanks !!


Solution

  • You can use apache commons io library. Specifically the FileUtils.listFiles static method

    Collection<File> allTxtFiles = FileUtils.listFiles(folder, new String[]{"txt"}, true)
    int count = allTxtFiles.size();
    

    Not sure if it will be faster, but it is generally good practice to use very popular open source libraries instead of reinventing the wheel because:

    1. you shouldn't spend time developing existing functionality,
    2. they most probably don't have bugs because have been used by a lot of people for long time,
    3. they were reviewed by lots of experienced programmers and most probably are very efficient and use fast algorithms and such,
    4. They are more readable by other developers and by you later on.

    Just try it out and see if it works for you.