How to list the files inside a JAR file?

前端 未结 16 2257
温柔的废话
温柔的废话 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:33

    CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
    if (src != null) {
      URL jar = src.getLocation();
      ZipInputStream zip = new ZipInputStream(jar.openStream());
      while(true) {
        ZipEntry e = zip.getNextEntry();
        if (e == null)
          break;
        String name = e.getName();
        if (name.startsWith("path/to/your/dir/")) {
          /* Do something with this entry. */
          ...
        }
      }
    } 
    else {
      /* Fail... */
    }
    

    Note that in Java 7, you can create a FileSystem from the JAR (zip) file, and then use NIO's directory walking and filtering mechanisms to search through it. This would make it easier to write code that handles JARs and "exploded" directories.

提交回复
热议问题