How to list the files inside a JAR file?

前端 未结 16 2234
温柔的废话
温柔的废话 2020-11-22 00:40

I have this code which reads all the files from a directory.

    File textFolder = new File(\"text_directory\");

    File [] texFiles = textFolder.listFiles         


        
16条回答
  •  不知归路
    2020-11-22 01:19

    One more for the road:

    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.nio.file.*;
    import java.util.ArrayList;
    import java.util.List;
    
    import static java.nio.file.FileSystems.newFileSystem;
    import static java.util.Collections.emptyMap;
    
    public class ResourceWalker {
      private static final PathMatcher FILE_MATCHER =
          FileSystems.getDefault().getPathMatcher( "glob:**.ttf" );
    
      public static List walk( final String directory )
          throws URISyntaxException, IOException {
        final List filenames = new ArrayList<>();
        final var resource = ResourceWalker.class.getResource( directory );
    
        if( resource != null ) {
          final var uri = resource.toURI();
          final var path = uri.getScheme().equals( "jar" )
              ? newFileSystem( uri, emptyMap() ).getPath( directory )
              : Paths.get( uri );
          final var walk = Files.walk( path, 10 );
    
          for( final var it = walk.iterator(); it.hasNext(); ) {
            final Path p = it.next();
            if( FILE_MATCHER.matches( p ) ) {
              filenames.add( p );
            }
          }
        }
    
        return filenames;
      }
    }
    

    This is a bit more flexible for matching specific filenames because it uses wildcard globbing.


    A more functional style:

    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.nio.file.*;
    import java.util.function.Consumer;
    
    import static java.nio.file.FileSystems.newFileSystem;
    import static java.util.Collections.emptyMap;
    
    /**
     * Responsible for finding file resources.
     */
    public class ResourceWalker {
      private static final PathMatcher FILE_MATCHER =
          FileSystems.getDefault().getPathMatcher( "glob:**.ttf" );
    
      public static void walk( final String dirName, final Consumer f )
          throws URISyntaxException, IOException {
        final var resource = ResourceWalker.class.getResource( dirName );
    
        if( resource != null ) {
          final var uri = resource.toURI();
          final var path = uri.getScheme().equals( "jar" )
              ? newFileSystem( uri, emptyMap() ).getPath( dirName )
              : Paths.get( uri );
          final var walk = Files.walk( path, 10 );
    
          for( final var it = walk.iterator(); it.hasNext(); ) {
            final Path p = it.next();
            if( FILE_MATCHER.matches( p ) ) {
              f.accept( p );
            }
          }
        }
      }
    }
    

提交回复
热议问题