문제

Java에서 게임을 만들고있는 게임을 만들고 있습니다. 여기서 항아리의 특정 디렉토리에 파일 목록을 만들고 싶어서 게임에서 사용할 클래스 목록을 가질 수 있습니다.

예를 들어 내 항아리에 디렉토리가 있습니다.

mtd/entity/creep/

해당 디렉토리의 모든 .class 파일 목록을 받고 싶습니다. 항아리의 다른 클래스에서 Java 코드를 사용합니다.

그렇게하기 가장 좋은 코드는 무엇입니까?

도움이 되었습니까?

해결책

Old 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();
        }
    }
}

다른 팁

아마도 가장 좋은 방법은 컴파일 시간에 클래스를 나열하는 것입니다.

깨지기 쉬운 런타임 접근법이 있습니다. 당신을 데려가십시오 Class (MyClass.classthis.getClass()). 부르다 getProtectionDomain. 부르다 getCodeSource. 부르다 getLocation. 부르다 openConnection. (또는 자원을 열면) 캐스트 JarURLConnection. 부르다 getJarFile. 부르다 entries. 확인을 통해 반복하십시오 getName. 나는이 접근법을 권장하지 않습니다.

기억 항아리 파일은 단지입니다 지퍼 이름이 바뀌고 내용을 읽기가 매우 쉽습니다. 지퍼 Java의 파일 :

    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);
        }
    }

Java는 클래스를로드 한 JAR 파일에 직접 액세스하지 않기 때문에 불가능합니다. Java.class.path 시스템 속성을 구문 분석하여 찾아 볼 수 있지만 모든 상황에서는 작동하지 않습니다. 또는 JAR 파일이있는 위치를 제한하거나 클래스 목록을 다른 방식으로 (예 : 매니페스트 파일을 통해) 제공 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top