Johanna
Johanna

Reputation: 27628

Searching for a file with .java extension

is there any way that at first filter all files with the extension as "java" and then search for finding some files with that extension? can you explain with a snippet code?thanks

Upvotes: 1

Views: 2100

Answers (4)

Ofek Gila
Ofek Gila

Reputation: 703

This is made easy using FileSearcher.java found on GitHub

An example of finding all .java files in your whole computer would look like:

public class FindDotJava {
    public static void main(String[] args) {
        ArrayList<File> dotJavaFiles = FileSearcher.findFiles(FileSearcher.SEARCH_EVERYTHING, "java");
    }
}

And you can just as easily only search the current folder or current folder + subfolders by changing SEARCH_EVERYTHING to CURRENT_FOLDER or SUBFOLDERS_AND_CURRENT.

I hope this helps!!!

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272237

If you need to do this in Java, the easiest way is to use Apache Commons IO and in particular FileUtils.iterateFiles().

Having said that, if this is a homework question I doubt you'll get many marks for using the above. I suspect the purpose of the homework is to test your ability to write recursive routines (there's a clue there!) - not find 3rd party libraries (a valuable skill in itself, mind).

Upvotes: 0

user267844
user267844

Reputation:

I also vote for Apache Commons.

http://www.kodejava.org/examples/359.html gves a usage example:

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

public class SearchFileRecursive {
    public static void main(String[] args) {
        File root = new File("/home/foobar/Personal/Examples");

        try {
            String[] extensions = {"xml", "java", "dat"};
            boolean recursive = true;

            //
            // Finds files within a root directory and optionally its
            // subdirectories which match an array of extensions. When the
            // extensions is null all files will be returned.
            //
            // This method will returns matched file as java.io.File
            //
            Collection files = FileUtils.listFiles(root, extensions, recursive);

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                System.out.println("File = " + file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 3

cx0der
cx0der

Reputation: 432

On Unix you can try find <dir> -name '*.java' -exec grep <search string> {} \;

Upvotes: 1

Related Questions