解压jar文件

来源:互联网 发布:cad软件二次开发 编辑:程序博客网 时间:2024/04/30 13:27

import java.io.*;
import java.util.jar.*;
import java.util.zip.*;
import java.util.*;
 
public class JarLoader extends ClassLoader
{
 public JarLoader() {}

 public synchronized void load(String archive, String outDir) throws IOException
 {
  ArrayList classes = new ArrayList();
  JarFile jf = new JarFile(archive);
  File dir = new File(outDir);
  if (!dir.exists())
   System.out.println(this.Mkdir(outDir, 2));

  for(Enumeration e = jf.entries(); e.hasMoreElements(); )
  {
   JarEntry je = (JarEntry)e.nextElement();
   //System.out.println(je.getName());
   if(je.getName().endsWith(".class"))
   {
    InputStream in = jf.getInputStream(je);
    File f = new File(outDir+File.separator+je.getName());
    f.createNewFile();
    OutputStream out =  new BufferedOutputStream(new FileOutputStream(f));
    byte[] buffer = new byte[2048];
    int nBytes = 0;
//    for (;;)  {
//     int nBytes = in.read(buffer);
//     if (nBytes <= 0) break;
//     out.write(buffer, 0, nBytes);
//    }
    while((nBytes = in.read(buffer)) > 0){
     out.write(buffer, 0, nBytes);
    }
    out.flush();
    out.close();
    in.close();
   }
  }
 }


 public String Mkdir(String path, int pos)
 {

  String msg = "";
  File dir = null;
  if (!path.endsWith("//")) path = path + "//";
  //System.out.println(path.length());
  if (path.indexOf("//", pos) <= 0){
   return msg;
  }else{
   if (pos < path.length()-1)
   {
    pos = path.indexOf("//", pos+1);
    //System.out.println(pos);
    //System.out.println(path.substring(0, pos));
    dir = new File(path.substring(0, pos));
    if (!dir.exists()) dir.mkdir();
    Mkdir(path, pos);
   }
  }
       
  return msg;
 }


 public static void main(String[] args)
 {
  try{
   JarLoader jl = new JarLoader();
   jl.load("moto.jar", "c://test//1//2//3//5//7//8//8//0//5//4");

  }catch(Exception e){
   System.out.println(e);
  }
 }


}