开发者

Searching for a file with .java extension

开发者 https://www.devze.com 2022-12-19 04:08 出处:网络
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?thanksI al

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


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


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


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


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!!!

0

精彩评论

暂无评论...
验证码 换一张
取 消