Total Pageviews

2014/05/23

How to get all files with specific name in a directory(including subdirectories) using Commons IO

Requirement
1. Search specific directory called "COP0407" 
2. Search through all directories called "COP0407" 


Supposed the directory is D:\psrdata\transfer\ftp\tofms, and has one subdirectory D:\psrdata\transfer\ftp\tofms\done




Solution
Apache commons IO package provide FileUtils for general file manipulation, here has two sample code
1. Search specific directory called "COP0407"  (exclude subdirectory)
   public static void main(String args[]) {  
     Collection files=  
     FileUtils.listFiles(new File(FmsBatchConfig.INPUT_FOLDER_PATH), //assign file path  
                    FileFilterUtils.prefixFileFilter("COP0407"), //assign file name  
                    FalseFileFilter.FALSE);//exclude subdirectories  
     //print file name  
     for(File file : files) {  
       System.out.println(file.getName());  
     }  
   }  

The console will print
 COP0407_01_1030501.txt  
 COP0407_01_1030502.txt  

2. Search through all directories called "COP0407" 
   public static void main(String args[]) {  
     Collection files=  
     FileUtils.listFiles(new File(FmsBatchConfig.INPUT_FOLDER_PATH), //assign file path  
                    FileFilterUtils.prefixFileFilter("COP0407"), //assign file name  
                    TrueFileFilter.TRUE);//include subdirectories  
     //print file name  
     for(File file : files) {  
       System.out.println(file.getName());  
     }  
   }  

The console will print
 COP0407_01_1030501.txt  
 COP0407_01_1030502.txt  
 COP0407_01_1030501 (2).txt  

Reference
[1] http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#listFiles(java.io.File, org.apache.commons.io.filefilter.IOFileFilter, org.apache.commons.io.filefilter.IOFileFilter)

No comments: