How to list the files inside a JAR file?

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

    erickson's answer worked perfectly:

    Here's the working code.

    CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
    List list = new ArrayList();
    
    if( src != null ) {
        URL jar = src.getLocation();
        ZipInputStream zip = new ZipInputStream( jar.openStream());
        ZipEntry ze = null;
    
        while( ( ze = zip.getNextEntry() ) != null ) {
            String entryName = ze.getName();
            if( entryName.startsWith("images") &&  entryName.endsWith(".png") ) {
                list.add( entryName  );
            }
        }
    
     }
     webimages = list.toArray( new String[ list.size() ] );
    

    And I have just modify my load method from this:

    File[] webimages = ... 
    BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex].getName() ));
    

    To this:

    String  [] webimages = ...
    
    BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex]));
    

提交回复
热议问题