Java 列出当前JAR文件目录中的文件

Java 列出当前JAR文件目录中的文件,java,class,jar,loading,Java,Class,Jar,Loading,我正在用JAVA制作一个游戏,我想在我的jar中的某个目录中列出一个文件列表,这样我就可以确保在游戏中使用这些类的列表 例如,假设在我的jar中有一个目录 mtd/entity/creep/ 我想使用jar中另一个类的java代码获取该目录中所有.class文件的列表 这样做的最佳代码是什么?旧的java1.4代码,但这会让您产生以下想法: private static List getClassesFromJARFile(String jar, String packageName) thr

我正在用JAVA制作一个游戏,我想在我的jar中的某个目录中列出一个文件列表,这样我就可以确保在游戏中使用这些类的列表

例如,假设在我的jar中有一个目录

mtd/entity/creep/
我想使用jar中另一个类的java代码获取该目录中所有.class文件的列表


这样做的最佳代码是什么?

旧的java1.4代码,但这会让您产生以下想法:

private static List getClassesFromJARFile(String jar, String packageName) throws Error
{
    final List classes = new ArrayList();
    JarInputStream jarFile = null;
    try
    {
        jarFile = new JarInputStream(new FileInputStream(jar));
        JarEntry jarEntry;
        do 
        {       
            try
            {
                jarEntry = jarFile.getNextJarEntry();
            }
            catch(IOException ioe)
            {
                throw new CCException.Error("Unable to get next jar entry from jar file '"+jar+"'", ioe);
            }
            if (jarEntry != null) 
            {
                extractClassFromJar(jar, packageName, classes, jarEntry);
            }
        } while (jarEntry != null);
        closeJarFile(jarFile);
    }
    catch(IOException ioe)
    {
        throw new CCException.Error("Unable to get Jar input stream from '"+jar+"'", ioe);
    }
    finally
    {
        closeJarFile(jarFile);
    }
   return classes;
}
private static void extractClassFromJar(final String jar, final String packageName, final List classes, JarEntry jarEntry) throws Error
{
    String className = jarEntry.getName();
    if (className.endsWith(".class")) 
    {
        className = className.substring(0, className.length() - ".class".length());
        if (className.startsWith(packageName))
        {
            try
            {
                classes.add(Class.forName(className.replace('/', '.')));
            } catch (ClassNotFoundException cnfe)
            {
                throw new CCException.Error("unable to find class named " + className.replace('/', '.') + "' within jar '" + jar + "'", cnfe);
            }
        }
    }
}
private static void closeJarFile(final JarInputStream jarFile)
{
    if(jarFile != null) 
    { 
        try
        {
            jarFile.close(); 
        }
        catch(IOException ioe)
        {
            mockAction();
        }
    }
}

这是不可能的,因为Java不提供对从中加载类的jar文件的直接访问。您可以尝试解析java.class.path系统属性来找到它,但这在所有情况下都不起作用。或者您可以限制jar文件必须驻留的位置,或者以不同的方式(例如通过清单文件)提供类的列表。

最好的方法可能是在编译时列出类


有一种脆弱的运行时方法。以
Class
this.getClass()的
MyClass.Class
)为例。调用
getProtectionDomain
。调用
getCodeSource
。调用
getLocation
。调用
openConnection
。(或者打开资源。)转换为
JarURLConnection
。调用
getJarFile
。调用
条目
。反复检查
getName
。我真的不推荐这种方法。

请记住,JAR文件只是重命名的ZIP文件,在Java中阅读ZIP文件的内容非常容易:

    File jarName = null;
    try
    {
        jarName = new File (Dir.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    }
    catch (Exception e)
    {
        e.printStackTrace();    
    }

    try 
    {
      ZipFile zf=new ZipFile(jarName.getAbsoluteFile());
      Enumeration e=zf.entries();
      while (e.hasMoreElements()) 
      {
          ZipEntry ze=(ZipEntry)e.nextElement();
          System.out.println(ze.getName());
      }
      zf.close();
   } catch (IOException e) 
   {
      e.printStackTrace();
   }

问题提出10年后,我提出了另一种方法:

private static void listFilesFromDirectoryInsideAJar(String pathToJar,String directory,String extension) {
        try {
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration<JarEntry> e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry candidat = e.nextElement();
                if (candidat.getName().startsWith(directory) && 
                    candidat.getName().endsWith(extension))
                    LOG.info(candidat.getName());
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(),e);
        }
    }
private static void list filesfromdirectoryindeajar(字符串路径、字符串目录、字符串扩展名){
试一试{
JarFile JarFile=新的JarFile(pathToJar);
枚举e=jarFile.entries();
而(e.hasMoreElements()){
JarEntry Candidate=e.nextElement();
if(candidate.getName().startsWith(目录)&&
candidate.getName().endsWith(扩展名))
LOG.info(candidate.getName());
}
}捕获(IOE异常){
LOG.error(e.getMessage(),e);
}
}

在稍微弄乱了一下之后,我让它开始工作了。非常感谢你!哦,这正是我现在需要的-谢谢!!这个答案怎么了?我假设更大的问题是找到jar文件的路径——实际上提取内容应该非常简单。