简体   繁体   中英

Finding files with .java extension in specified folder

Task :

Write a Java application that accepts two file names as arguments: dirName and fileName Find all non-directory files contained in directory dirName whose name ends in ".java"

I tried to use this code but how can I print out the files ending with ".java" ? It's the first time I work with this things and I don't know how to use them.

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public static File[] finder(String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() { 
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".txt"); }
        });

    }

    public static void main(String[] args){
        String dirName = "src";
        System.out.println(finder(dirName));

    }

}
return !dir.isDirectory() && filename.endsWith(".java");

Thanks for the help. It works fine now .

 import java.io.*; public class Filter { public static File[] finder(String dirName) { File dir = new File(dirName); return dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(".java"); } }); } public static void main(String[] args) { String dirName = "src"; File[] files = finder(dirName); for (File i: files) System.out.println(i.getName()); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM