简体   繁体   English

getResources()仅返回1个对象的枚举

[英]getResources() return enumeration with only 1 object

I try to get the list of files from classpath (web-inf/classes/dir). 我尝试从类路径(web-inf / classes / dir)获取文件列表。

Enumeration<URL> en = getClass().getClassLoader().getResources("dir");

However, instead of elements in this folder, the only element is the folder itself. 但是,唯一的元素是文件夹本身,而不是此文件夹中的元素。 Is there a way I can get the list of files, or the only way is to access file one by one. 有没有一种方法可以获取文件列表,或者唯一的方法是逐个访问文件。 Because when I try to refer to some file in the same folder, I can easily access its contents. 因为当我尝试引用同一文件夹中的某个文件时,我可以轻松访问其内容。

You can't browse a directory on the classpath recursively. 您不能递归浏览类路径上的目录。

See this post: How to use ClassLoader.getResources() correctly? 看到这篇文章: 如何正确使用ClassLoader.getResources()?

If you know you're looking at a JAR file however, you might open it directly as an archive and browse the files. 但是,如果您知道要查看的是JAR文件,则可以直接将其作为存档打开并浏览文件。

Somebody came up with a useful answer for this question: Get all of the Classes in the Classpath 有人为这个问题提出了一个有用的答案: 在类路径中获取所有类

You could adapt this code to browse through all JAR files and directories on your classpath and apply some filter for your directory name yourself. 您可以修改此代码以浏览类路径上的所有JAR文件和目录,并自己为目录名称应用一些过滤器。 The example will list all classes from the gnu.trove.* package: 该示例将列出gnu.trove。*包中的所有类:

import java.io.File;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Test
{

    public static void main(String[] args)
    {
        final String dirname = "gnu.trove.";

        findClasses(new Visitor<String>() {

            @Override
            public boolean visit(String classname)
            {
                if (classname.startsWith(dirname)) {
                    System.out.println(classname);
                }
                return true;
            }
        });
    }

    public interface Visitor<T>
    {
        public boolean visit(T t);
    }

    public static void findClasses(Visitor<String> visitor)
    {
        String classpath = System.getProperty("java.class.path");
        String[] paths = classpath.split(System.getProperty("path.separator"));

        String javaHome = System.getProperty("java.home");
        File file = new File(javaHome + File.separator + "lib");
        if (file.exists()) {
            findClasses(file, file, true, visitor);
        }

        for (String path : paths) {
            file = new File(path);
            if (file.exists()) {
                findClasses(file, file, true, visitor);
            }
        }
    }

    private static boolean findClasses(File root, File file,
            boolean includeJars, Visitor<String> visitor)
    {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                if (!findClasses(root, child, includeJars, visitor)) {
                    return false;
                }
            }
        } else {
            if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file);
                } catch (Exception ex) {

                }
                if (jar != null) {
                    Enumeration<JarEntry> entries = jar.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        int extIndex = name.lastIndexOf(".class");
                        if (extIndex > 0) {
                            if (!visitor.visit(name.substring(0, extIndex)
                                    .replace("/", "."))) {
                                return false;
                            }
                        }
                    }
                }
            } else if (file.getName().toLowerCase().endsWith(".class")) {
                if (!visitor.visit(createClassName(root, file))) {
                    return false;
                }
            }
        }

        return true;
    }

    private static String createClassName(File root, File file)
    {
        StringBuffer sb = new StringBuffer();
        String fileName = file.getName();
        sb.append(fileName.substring(0, fileName.lastIndexOf(".class")));
        file = file.getParentFile();
        while (file != null && !file.equals(root)) {
            sb.insert(0, '.').insert(0, file.getName());
            file = file.getParentFile();
        }
        return sb.toString();
    }

}

Here is some code for ignoring JAR files and just going through the files on directories on your classpath: 这是一些代码,用于忽略JAR文件,而仅遍历类路径上目录中的文件:

import java.io.File;

public class Test
{

    public static void main(String[] args)
    {
        findClasses(new Visitor<String>() {

            @Override
            public boolean visit(String classname)
            {
                // apply your filtering here
                System.out.println(classname);
                return true;
            }
        });
    }

    public interface Visitor<T>
    {
        public boolean visit(T t);
    }

    public static void findClasses(Visitor<String> visitor)
    {
        String classpath = System.getProperty("java.class.path");
        String[] paths = classpath.split(System.getProperty("path.separator"));

        for (String path : paths) {
            File file = new File(path);
            // Ignore JAR files, just go through directories on the classpath
            if (file.isFile()) {
                continue;
            }
            findFiles(file, file, visitor);
        }
    }

    private static boolean findFiles(File root, File file,
            Visitor<String> visitor)
    {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                if (!findFiles(root, child, visitor)) {
                    return false;
                }
            }
        } else {
            if (!visitor.visit(createRelativePath(root, file))) {
                return false;
            }
        }

        return true;
    }

    private static String createRelativePath(File root, File file)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(file.getName());
        file = file.getParentFile();
        while (file != null && !file.equals(root)) {
            sb.insert(0, '/').insert(0, file.getName());
            file = file.getParentFile();
        }
        return sb.toString();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM