题
我在做的JAVA游戏,我想拿出在我的罐子某个目录的文件列表,所以我可以确保有在游戏中使用这些类的列表。
举例说在我的罐子我有一个目录
mtd/entity/creep/
我想在该目录中的所有.class文件的列表在罐子里使用Java代码从另一个类
什么是这样做的最好的代码?
解决方案
旧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.class
的this.getClass()
)。呼叫getProtectionDomain
。呼叫getCodeSource
。呼叫getLocation
。呼叫openConnection
。 (或者打开资源。)演员来JarURLConnection
。呼叫getJarFile
。呼叫entries
。通过检查getName
迭代。我真的不推荐这种方法。
记住 JAR 文件只是邮政编码重命名的文件,这是非常容易阅读的邮政编码在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文件具有驻留,或者(通过清单文件例如)以不同的方式提供的类的列表。
不隶属于 StackOverflow