public static String [ ] listResourceFiles ( Class < ? > clazz , String resourceDirName ) throws URISyntaxException , IOException { if ( ! resourceDirName . endsWith ( "/" ) ) { resourceDirName = resourceDirName + "/" ; } URL dirURL = clazz . getResource ( resourceDirName ) ; if ( dirURL == null ) { throw new IOException ( "Resource directory " + resourceDirName + " not found" ) ; } if ( dirURL . getProtocol ( ) . equals ( "file" ) ) { File [ ] entries = new File ( dirURL . toURI ( ) ) . listFiles ( File :: isFile ) ; String [ ] fileNames = new String [ entries . length ] ; for ( int i = 0 ; i < entries . length ; i ++ ) { fileNames [ i ] = entries [ i ] . toString ( ) ; } return fileNames ; } if ( dirURL . getProtocol ( ) . equals ( "jar" ) ) { String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( "!" ) ) ; //strip out only the JAR file try ( JarFile jar = new JarFile ( jarPath ) ) { Enumeration < JarEntry > entries = jar . entries ( ) ; //gives ALL entries in jar List < String > result = new ArrayList <> ( ) ; String relativeResourceDirName = resourceDirName . startsWith ( "/" ) ? resourceDirName . substring ( 1 ) : resourceDirName ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( relativeResourceDirName ) && ! name . equals ( relativeResourceDirName ) ) { //filter according to the path String entry = name . substring ( relativeResourceDirName . length ( ) ) ; int checkSubdir = entry . indexOf ( "/" ) ; if ( checkSubdir < 0 ) { // not a subdirectory result . add ( entry ) ; } } } return result . toArray ( new String [ result . size ( ) ] ) ; } } throw new UnsupportedOperationException ( "Cannot list files for URL " + dirURL ) ; }
List directory files in a resource folder . Not recursive . Works for regular files and also JARs .