Get a list of resources from classpath directory

前端 未结 14 1182
予麋鹿
予麋鹿 2020-11-22 05:20

I am looking for a way to get a list of all resource names from a given classpath directory, something like a method List getResourceNames (String direct

14条回答
  •  清歌不尽
    2020-11-22 05:57

    I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem it looks like you can treat the objects in that ZIP as a "regular" file.

    In the linked documentation above:

    Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.

    Once you have an instance of a zip file system, you can invoke the methods of the [java.nio.file.FileSystem][3] and [java.nio.file.Path][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.

    The documentation for the jdk.zipfs module in [Java 11 states][5]:

    The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [FileSystems.newFileSystem][6] if installed.

    Here is a contrived example I did using your example resources. Note that a .zip is a .jar, but you could adapt your code to instead use classpath resources:

    Setup

    cd /tmp
    mkdir -p x/y/z
    touch x/y/z/{a,b,c}.html
    echo 'hello world' > x/y/z/d
    zip -r example.zip x
    

    Java

    import java.io.IOException;
    import java.net.URI;
    import java.nio.file.FileSystem;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.util.Collections;
    import java.util.stream.Collectors;
    
    public class MkobitZipRead {
    
      public static void main(String[] args) throws IOException {
        final URI uri = URI.create("jar:file:/tmp/example.zip");
        try (
            final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
        ) {
          Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
          System.out.println("-----");
          final String manifest = Files.readAllLines(
              zipfs.getPath("x", "y", "z").resolve("d")
          ).stream().collect(Collectors.joining(System.lineSeparator()));
          System.out.println(manifest);
        }
      }
    
    }
    

    Output

    Files in zip:/
    Files in zip:/x/
    Files in zip:/x/y/
    Files in zip:/x/y/z/
    Files in zip:/x/y/z/c.html
    Files in zip:/x/y/z/b.html
    Files in zip:/x/y/z/a.html
    Files in zip:/x/y/z/d
    -----
    hello world
    

提交回复
热议问题