这期内容当中小编将会给大家带来有关Jar中的文件怎么利用Java进行读取,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
Java读取Jar中的文件
实现代码:
import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.IOUtils; public class ResourceLoadFromJarUtil { public static void main(String[] args) throws IOException { String resourcePath = "struts-plugin.xml"; String[] cps = System.getProperty("java.class.path").split(";"); for (String cp : cps) { if (!cp.endsWith(".jar")) { continue; } InputStream in = loadResourceFromJarFile(cp, resourcePath); if (in != null) { System.err.println(IOUtils.toString(in)); in.close(); } } for (String cp : cps) { if (!cp.endsWith(".jar")) { continue; } InputStream in = loadResourceFromJarURL(cp, resourcePath); if (in != null) { System.err.println(IOUtils.toString(in)); in.close(); } } InputStream in = loadResourceFromJarURL( "http://localhost:8080/SpringStruts2Integration/struts2-spring-plugin-2.3.4.1.jar", resourcePath); if (in != null) { System.err.println(IOUtils.toString(in)); in.close(); } } public static InputStream loadResourceFromJarFile(String jarPath, String resPath) { if (!jarPath.endsWith(".jar")) { return null; } try { JarFile jarFile = new JarFile(jarPath); JarEntry jarEntry = jarFile.getJarEntry(resPath); if (jarEntry == null) { return null; } return jarFile.getInputStream(jarEntry); } catch (IOException e) { e.printStackTrace(); 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(); JarEntry jarEntry = jarFile.getJarEntry(resPath); if (jarEntry == null) { return null; } return jarFile.getInputStream(jarEntry); } catch (IOException e) { e.printStackTrace(); return null; } } }
上述就是小编为大家分享的Jar中的文件怎么利用Java进行读取了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注编程网行业资讯频道。