下面的代码可以枚举所有的 "META-INF/MANIFEST.MF",你还可以观察到在类路径中哪些 jar 文件包含有该资源:
import java.net.URL;
import java.util.Enumeration;
public class Test {
public static void main(String[] args) throws Exception {
ClassLoader ldr = Test.class.getClassLoader();
System.out.println("## Test for getResources(‘META-INF/MANIFEST.MF') ##");
Enumeration<URL> urls = ldr.getResources("META-INF/MANIFEST.MF");
while(urls.hasMoreElements())
System.out.println(urls.nextElement());
下面的代码演示了如何正确获取代码的类路径起点:
package test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
* 演示如何获取当前类路径的起点
* @author Chen Zhiqiang <chenzhiqiang@mail.com>
public class AppDirTest {
Classcls = AppDirTest.class;
URL codeLocation = getCodeLocation();
* Get the code location.
* Return the classpath where the code run from. The return url will be:
* file:/path/my-app/calsses/ or file:/path/my-app/my-app.jar
* @return URL
public URL getCodeLocation() {
if (codeLocation != null)
return codeLocation;
// Get code location using the CodeSource
codeLocation = cls.getProtectionDomain().getCodeSource().getLocation();
if (codeLocation != null)
return codeLocation;
// If CodeSource didn't work, use {@link } Class.getResource instead.
URL r = cls.getResource("");
synchronized (r) {
String s = r.toString();
Pattern jar_re = Pattern.compile("jar:\\s?(.*)!/.*");
Matcher m = jar_re.matcher(s);
if (m.find()) { // the code is run from a jar file.
s = m.group(1);
} else {
String p = cls.getPackage().getName().replace('.', '/');
s = s.substring(0, s.lastIndexOf(p));
try {
codeLocation = new URL(s);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
return codeLocation;
* Get the class path root where the program startup, if run in a jar,
* return the jar file's parent path.
* @return
public String getAppDir() {
File f = new File(getCodeLocation().getPath());
return f.isFile() ? f.getParent() : f.getPath();
public static void main(String[] args) {
AppDirTest t = new AppDirTest();
System.out.println("code location: " + t.getCodeLocation());
System.out.println("app dir: " + t.getAppDir());