1. 程式人生 > >java 獲取 jar 包內檔案列表

java 獲取 jar 包內檔案列表

   獲取 jar 包內檔案列表,使用 JarFile。下面是我的測試類:

package com.zd.test1;

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

public class TestJarFile {

	public static void main(String[] args) throws IOException {
		File path = new File(System.getProperty("user.dir") + "/" + "zd" + "/");
		
		File[] jarFiles =  path.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File file) {
				return file.getName().toUpperCase().endsWith("JAR");
			}
		});
		
		JarFile jf = null;
		for(File fileTemp : jarFiles){
			jf = new JarFile(fileTemp);
			Enumeration<JarEntry> enume = jf.entries();
			while(enume.hasMoreElements()){
				JarEntry element = enume.nextElement();
				String name = element.getName();
				if(name.toUpperCase().endsWith(".CLASS")){
					System.out.println(name);
				}
			}
		}
	}
	
}

輸出結果如下:

org/apache/commons/logging/impl/Log4JCategoryLog.class
org/apache/commons/logging/impl/Log4JLogger.class
org/apache/commons/logging/impl/Log4jFactory.class
org/apache/commons/logging/impl/LogFactoryImpl$1.class
org/apache/commons/logging/impl/LogFactoryImpl.class
org/apache/commons/logging/impl/LogKitLogger.class
org/apache/commons/logging/impl/NoOpLog.class
org/apache/commons/logging/impl/SimpleLog$1.class
org/apache/commons/logging/impl/SimpleLog.class
org/apache/commons/logging/impl/AvalonLogger.class
org/apache/commons/logging/impl/Jdk14Logger.class
org/apache/commons/logging/Log.class
org/apache/commons/logging/LogFactory$1.class
org/apache/commons/logging/LogFactory$2.class
org/apache/commons/logging/LogFactory$3.class
org/apache/commons/logging/LogFactory.class
org/apache/commons/logging/LogConfigurationException.class
org/apache/commons/logging/LogSource.class