import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ResourceLoadFromJarUtil {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
loadResourceFromJarURL("C:\\eclipse-workspace\\dominos-user\\target\\x'x-user.jar", "");
}
/**
* 读取Jar文件中的资源
*
* @param jarUrl 本地jar文件或网络上(ttp://host:port/subpath/jarfile.jar)jar文件路径
* @param resPath 资源文件所在jar中的路径(不能以'/'字符开头)
* @return 如果资源加载失败,返回null
*/
public static InputStream loadResourceFromJarURL(String jarUrl, String resPath) {
if (!jarUrl.endsWith(".jar")) {
return null;
}
URL url = null;
if (jarUrl.startsWith("http://")) {
try {
url = new URL("jar:" + jarUrl + "!/");
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
} else {
try {
url = new URL("jar:file:/" + jarUrl + "!/");
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
try {
JarURLConnection jarURLConnection;
jarURLConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = jarURLConnection.getJarFile();
for (Enumeration e = jarFile.entries(); e.hasMoreElements();) { // 这个循环会读取jar包中所有文件,包括文件夹
JarEntry jarEntry = e.nextElement();// jarEntry就是我们读取的jar包中每一个文件了,包括目录
if(jarEntry.getName().endsWith(".jar")) {
System.out.println(jarEntry.getName());
// URLClassLoader myClassLoader = new URLClassLoader(new URL[]{jarEntry.}, Thread.currentThread().getContextClassLoader());
}
}
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}