Reputation: 1418
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.
Upvotes: 5
Views: 9472
Reputation: 1108642
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
.
Upvotes: 9