How to list the files inside a JAR file?

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

    Here's a method I wrote for a "run all JUnits under a package". You should be able to adapt it to your needs.

    private static void findClassesInJar(List classFiles, String path) throws IOException {
        final String[] parts = path.split("\\Q.jar\\\\E");
        if (parts.length == 2) {
            String jarFilename = parts[0] + ".jar";
            String relativePath = parts[1].replace(File.separatorChar, '/');
            JarFile jarFile = new JarFile(jarFilename);
            final Enumeration entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                final JarEntry entry = entries.nextElement();
                final String entryName = entry.getName();
                if (entryName.startsWith(relativePath)) {
                    classFiles.add(entryName.replace('/', File.separatorChar));
                }
            }
        }
    }
    

    Edit: Ah, in that case, you might want this snippet as well (same use case :) )

    private static File findClassesDir(Class clazz) {
        try {
            String path = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
            final String codeSourcePath = URLDecoder.decode(path, "UTF-8");
            final String thisClassPath = new File(codeSourcePath, clazz.getPackage().getName().repalce('.', File.separatorChar));
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError("impossible", e);
        }
    }
    

提交回复
热议问题