// 获取当前项目路径, Main是当前类, 可以指定其它类, 这个无所谓
String pathname = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("当前路径: " + pathname);
// 使用JarFile打开jar文件
JarFile jar = null;
try {
jar = new JarFile(pathname);
Enumeration<JarEntry> entryEnumeration = jar.entries();
while (entryEnumeration.hasMoreElements()) {
// 获取JarEntry对象
JarEntry entry = entryEnumeration.nextElement();
// 获取当前JarEntry对象的路径+文件名
System.out.println(entry.getName());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭jar文件
jar.close();
} catch (IOException e) {
e.printStackTrace();
}
}
项目结构
结果
当前路径: /C:/Users/18528/Desktop/rjar.jar
META-INF/MANIFEST.MF
META-INF/
a/
a/A.class
a/b/
a/b/B.class
a/b/c/
a/b/c/C.class
Main.class
直接在IDE执行是看不到效果的,需要打包为jar。可以判断当前是否为jar,如果是则采用此方法,否则也通过 Main.class.getProtectionDomain().getCodeSource().getLocation().getPath() 获取当前项目路径去遍历目录