How to list the files inside a JAR file?

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

    Some time ago I made a function that gets classess from inside JAR:

    public static Class[] getClasses(String packageName) 
    throws ClassNotFoundException{
        ArrayList classes = new ArrayList ();
    
        packageName = packageName.replaceAll("\\." , "/");
        File f = new File(jarName);
        if(f.exists()){
            try{
                JarInputStream jarFile = new JarInputStream(
                        new FileInputStream (jarName));
                JarEntry jarEntry;
    
                while(true) {
                    jarEntry=jarFile.getNextJarEntry ();
                    if(jarEntry == null){
                        break;
                    }
                    if((jarEntry.getName ().startsWith (packageName)) &&
                            (jarEntry.getName ().endsWith (".class")) ) {
                        classes.add(Class.forName(jarEntry.getName().
                                replaceAll("/", "\\.").
                                substring(0, jarEntry.getName().length() - 6)));
                    }
                }
            }
            catch( Exception e){
                e.printStackTrace ();
            }
            Class[] classesA = new Class[classes.size()];
            classes.toArray(classesA);
            return classesA;
        }else
            return null;
    }
    

提交回复
热议问题