2011-11-30 5 views
5

मैं रिकर्सिव तरीके से निर्देशिका में .class फ़ाइलों को सूचीबद्ध करने के लिए एक साधारण प्रोग्राम कोडिंग कर रहा हूं।FileNameFilter और FileFilter का उपयोग

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 

लेकिन इस सूची में केवल निर्देशिका और उप निर्देशिकाओं, फ़ाइल नहीं:

शुरू में मैं इस कोडित!

मैं 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 

और यह काम, फ़ाइल .class लिस्टिंग।

मैं FileFilter और FilenameFilter के बीच अंतर को पढ़ लेकिन मैं व्यवहार के अंतर के कारण नहीं मिला है।

+0

क्या "। \\" का मतलब है? –

+0

वर्तमान निर्देशिका, "।" के रूप में। – alepuzio

उत्तर

9

dirFilenameFilter#accept() में तर्क उस मूल निर्देशिका का प्रतिनिधित्व करता है जो फ़ाइल में पाया गया था, फ़ाइल की तरह ही आप अपेक्षा करते हैं। तो दूसरों के बीच dir.isFile() आपके FilenameFilter दृष्टिकोण में हमेशा false लौटाएगा जो acceptByteCode() हमेशा false लौटाएगा।

संबंधित मुद्दे