views:

158

answers:

3

Hi, 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

+1  A: 

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

cx0der
I suspect that her homework problem involves writing some Java code to do the work.
Pointy
www.betterthangrep.com - 'ack' is a more powerful code search tool than the above. Recommended.
Brian Agnew
A: 

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).

Brian Agnew
+4  A: 

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();
        }
    }
}
Junky