How to walk through Java class resources?

后端 未结 5 1993
栀梦
栀梦 2020-12-13 20:35

I know we can do something like this:

Class.class.getResourceAsStream(\"/com/youcompany/yourapp/module/someresource.conf\")

to read the fil

相关标签:
5条回答
  • 2020-12-13 21:16

    I've been looking for a way to list the contents of a jar file using the classloaders, but unfortunately this seems to be impossible. Instead what you can do is open the jar as a zip file and get the contents this way. You can use standard (here) ways to read the contents of a jar file and then use the classloader to read the contents.

    0 讨论(0)
  • 2020-12-13 21:25

    The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)

    List<String> resourceNames;
    try (ScanResult scanResult = new ClassGraph()
                .whitelistPaths("com/yourcompany/yourapp")
                .scan()) {
        resourceNames = scanResult.getAllResources().getNames();
    }
    
    0 讨论(0)
  • 2020-12-13 21:29

    In general can't get a list of resources like this. Some classloaders may not even be able to support this - imagine a classloader which can fetch individual files from a web server, but the web server doesn't have to support listing the contents of a directory. For a jar file you can load the contents of the jar file explicitly, of course.

    (This question is similar, btw.)

    0 讨论(0)
  • 2020-12-13 21:30

    For resources in a JAR file, something like this works:

    URL url = MyClass.class.getResource("MyClass.class");
    String scheme = url.getProtocol();
    if (!"jar".equals(scheme))
      throw new IllegalArgumentException("Unsupported scheme: " + scheme);
    JarURLConnection con = (JarURLConnection) url.openConnection();
    JarFile archive = con.getJarFile();
    /* Search for the entries you care about. */
    Enumeration<JarEntry> entries = archive.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      if (entry.getName().startsWith("com/y/app/")) {
        ...
      }
    }
    

    You can do the same thing with resources "exploded" on the file system, or in many other repositories, but it's not quite as easy. You need specific code for each URL scheme you want to support.

    0 讨论(0)
  • 2020-12-13 21:39

    I usually use

    getClass().getClassLoader().getResourceAsStream(...)
    

    but I doubt you can list the entries from the classpath, without knowing them a priori.

    0 讨论(0)
提交回复
热议问题