JAR解壓縮方法
作者:hunhun1981
出自:http://blog.csdn.net/hunhun1981/
下面這些代碼,是用來解壓jar檔案的(我自己寫了一個打包工具,專門用於修改設定檔並對原始JAR進行二次發布)。
第一種是使用JarFile類來完成功能,大家可以稍加修改,整合ClassLoader既可以實現一個自解壓的JAR包。
package otheri;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;/** * * @author hunhun1981 <hunhun1981@hotmail.com> */public class JARDecompressionTool { public static synchronized void decompress(String fileName, String outputPath) throws IOException { if (!outputPath.endsWith(File.separator)) { outputPath += File.separator; } File dir = new File(outputPath); if (!dir.exists()) { dir.mkdir(); } JarFile jf = new JarFile(fileName); for (Enumeration e = jf.entries(); e.hasMoreElements();) { JarEntry je = (JarEntry) e.nextElement(); String outFileName = outputPath + je.getName(); File f = new File(outFileName); if (outFileName.endsWith("/") || outFileName.endsWith("//") || outFileName.endsWith(File.separator)) { f.mkdir(); } else { InputStream in = jf.getInputStream(je); OutputStream out = new BufferedOutputStream(new FileOutputStream(f)); byte[] buffer = new byte[2048]; int nBytes = 0; while ((nBytes = in.read(buffer)) > 0) { out.write(buffer, 0, nBytes); } out.flush(); out.close(); in.close(); } } }}
第二種是使用ant,代碼中還附帶了jar的打包和wtk簽名的方法。使用前請先整合ant和antenna。
package otheri.j2mePackageTools;import de.pleumann.antenna.WtkSign;import java.io.File;import org.apache.tools.ant.Project;import org.apache.tools.ant.taskdefs.Expand;import org.apache.tools.ant.taskdefs.Jar;import org.apache.tools.ant.types.FileSet;/** * * @author hunhun1981 <hunhun1981@hotmail.com> */public class JARUtils { public static void jarPackage(File srcPath, File manifest, String manifestEncoding, File output) { Project prj = new Project(); Jar jar = new Jar(); jar.setProject(prj); jar.setDestFile(output); FileSet fileSet = new FileSet(); fileSet.setProject(prj); fileSet.setDir(srcPath); fileSet.setIncludes("**/*.*"); jar.addFileset(fileSet); jar.setManifest(manifest); jar.setManifestEncoding(manifestEncoding); jar.execute(); } public static void jarExpand(File jarFile, File outputPath) { Project prj = new Project(); Expand expand = new Expand(); expand.setProject(prj); expand.setSrc(jarFile); expand.setOverwrite(true); expand.setDest(outputPath); expand.execute(); } public static void wtkSign(File jadFile, File jarFile, File keyStoreFile, String storePass, String cerAlias, String cerPass) { Project prj = new Project(); WtkSign wtk = new WtkSign(); wtk.setProject(prj); wtk.setJadFile(jadFile); wtk.setJarFile(jarFile); wtk.setKeyStore(keyStoreFile); wtk.setStorePass(storePass); wtk.setCertAlias(cerAlias); wtk.setCertPass(cerPass); wtk.execute(); }}
更多資訊,請關注hunhun1981的專欄 。