public static List < File > findFiles ( final String startDir , final Set < String > fileNamePatterns ) { /* file names to be returned */ final List < File > files = new ArrayList < File > ( ) ; /* Stack to hold potential sub directories */ final Stack < File > dirs = new Stack < File > ( ) ; /* start directory */ final File startdir = new File ( startDir ) ; if ( ! startdir . exists ( ) ) { throw new CitrusRuntimeException ( "Test directory " + startdir . getAbsolutePath ( ) + " does not exist" ) ; } if ( startdir . isDirectory ( ) ) { dirs . push ( startdir ) ; } /* walk through the directories */ while ( dirs . size ( ) > 0 ) { final File file = dirs . pop ( ) ; File [ ] foundFiles = file . listFiles ( ( dir , name ) -> { File tmp = new File ( dir . getPath ( ) + File . separator + name ) ; boolean accepted = tmp . isDirectory ( ) ; for ( String fileNamePattern : fileNamePatterns ) { if ( fileNamePattern . contains ( "/" ) ) { fileNamePattern = fileNamePattern . substring ( fileNamePattern . lastIndexOf ( ' ' ) + 1 ) ; } fileNamePattern = fileNamePattern . replace ( "." , "\\." ) . replace ( "*" , ".*" ) ; if ( name . matches ( fileNamePattern ) ) { accepted = true ; } } /* Only allowing XML files as spring configuration files */ return accepted && ! name . startsWith ( "CVS" ) && ! name . startsWith ( ".svn" ) && ! name . startsWith ( ".git" ) ; } ) ; for ( File found : Optional . ofNullable ( foundFiles ) . orElse ( new File [ ] { } ) ) { /* Subfolder support */ if ( found . isDirectory ( ) ) { dirs . push ( found ) ; } else { files . add ( found ) ; } } } return files ; }
Method to retrieve all files with given file name pattern in given directory . Hierarchy of folders is supported .