2

I need to scan a particular folder in Java, and be able to return the integer number of files of a particular type (based on not only extension but also naming convention.) For example, I want to know how many JPG files there are in the \src folder that have a simple integer filename (say, 1.JPG through 30.JPG). Can anyone point me in the right direction? Thx

2 Answers 2

10

java.io.File.list(FilenameFilter) is the method you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

1

I have a method that uses a regex pattern for a rather complicated file structure. Something like that could be used, although I'm sure it could be written more concisely than my example (edited for security).

/**
     * Get all non-directory filenames from a given foo/flat directory
     * 
     * @param network
     * @param typeRegex
     * @param locationRegex
     * @return
     */
    public List<String> getFilteredFilenames(String network, String typeRegex, String locationRegex) {

        String regex = null;

        List<String> filenames = new ArrayList<String>();
        String directory;

        // Look at the something network
        if (network.equalsIgnoreCase("foo")) {

            // Get the foo files first
            directory = this.pathname + "/" + "foo/filtered/flat";
            File[] foofiles = getFilenames(directory);

            // run the regex if need be.
            if (locationRegex != null && typeRegex != null ) {
                regex = typeRegex + "." + locationRegex;

                //System.out.println(regex);
            }


            for (int i = 0; i < foofiles.length; i++) {
                if (foofiles[i].isFile()) {
                    String file = foofiles[i].getName();

                    if (regex == null) {
                        filenames.add(file);
                    }
                    else {
                        if (file.matches(regex)) {
                            filenames.add(file);
                        }
                    }
                }
            }
        }

        return filenames;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.