Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of FileNameFilter and FileFilter

I'm coding a simple program to list the files .class in a directory in recursive way.

Initially I coded this:

public class Parsing{

    public static void main(String[] args) {
        File f=new  File(".\\");
        readRecursive(f);
    }

    private static void readRecursive(File f) {
        String[] files=f.list(  new FilterByteCode());
        if(null==files){
            files=new String[0];
        }
        for(String curr: files){
            File currFile=new File(curr);
            System.out.println(currFile.getName());
            readRecursive(currFile);
        }
    }
}//end parsing

class FilterByteCode implements FilenameFilter {


    @Override
    public boolean accept(File dir, String name) {
        if(name.endsWith(".class")){
            return acceptByteCode(dir);
        }else{
            return  (null!=dir && dir.exists() && dir.isDirectory());
        }

    }

        private boolean acceptByteCode(File dir) {
            boolean res= (null!=dir && dir.exists() && dir.isFile());
            return res;
        }

}//FilterByteCode 

But this list only the directory and subdirectories, not the file!

I solved using the FileFilter:

private static void readRecursiveFile(File f) {
        File[] files=f.listFiles(new FilterByteCode2());
        if(null==files){
            files=new File[0];
        }
        for(File curr: files){
            System.out.println(curr.getName());
            readRecursiveFile(curr);
        }
    }

class FilterByteCode2 implements FileFilter {

    @Override
    public boolean accept(File pathname) {
        if(null!=pathname && pathname.getName().endsWith(".class")){
            return  acceptByteCode(pathname);
        }else{
            return (null!=pathname && pathname.exists() && pathname.isDirectory());
        }
    }//accept

    private boolean acceptByteCode(File dir) {
        boolean res = (null != dir && dir.exists() && dir.isFile());
        return res;
    }

}//FilterByteCode2

and this work, listing the file .class.

I read the difference between the FileFilter and FilenameFilter but I don't found the cause of difference of behaviour.

like image 508
alepuzio Avatar asked Nov 30 '11 14:11

alepuzio


1 Answers

The dir argument in FilenameFilter#accept() represents the parent directory the file was found in, not the file itself as you seem to expect. So among others dir.isFile() will always return false in your FilenameFilter approach which makes that acceptByteCode() will always return false.

like image 170
BalusC Avatar answered Oct 04 '22 00:10

BalusC