posts - 1,  comments - 25,  trackbacks - 0

如果已存在以压缩文件a.jar,现在想把一个a.class文件或com/my/b.calss包含文件夹的文件添加到压缩包中;

1.创建临时文件

2..先解压目标压缩Jar文件 到临时文件夹

3.拷贝源文件到临时文件夹

4.再压缩临时文件夹

5.再删除临时文件夹

方法可能有些笨,但是我找了好久也没找到现成API实现这个功能。所以和大家分享,共写了三个类

第一个类:

package com.jar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 文件夹或文件拷贝到指定目录
* 文件夹的删除
* @author zhang
*
*/
public class FolderCopy {

/**
* 测试主程序
*/
public static void main(String args[]) throws IOException {
   String url1 = "D:/wtk/SonyEricsson/JavaME_SDK_CLDC/README.html";
   String url2 = "c:/temp/";
   copyDirectiory(url1, url2);
}
/**
* 文件夹拷贝,将源文件夹下的所有文件及其子文件夹(文件)拷贝到目标文件夹(文件)下

* @param sourceFile
*            源文件夹或文件
* @param desFile
*            目标文件夹
* @return
*/
public static boolean copyDirectiory(String sourceFile, String desFile)
    throws IOException {
   File des = new File(desFile);
   if (!des.exists())
    des.mkdirs();// 不存在目标文件夹就创建
  
   File source = new File(sourceFile);
   if (!source.exists()) {
    System.out.println(source.getAbsolutePath()
      + "========源文件不存在!=======");
    return false;
   }
   FileInputStream input = null;
   FileOutputStream output = null;

   try {
    if (source.isFile()) { // 如果是文件 则读源文件 写入目标文件
     input = new FileInputStream(source);
     File f = new File(desFile + "/"
       + source.getName());
     output = new FileOutputStream(f);
     byte[] b = new byte[1024 * 5];
     int len;
     while ((len = input.read(b)) != -1) { // 读文件
      output.write(b, 0, len); // 向目标文件写文件
     }
     input.close();
     output.flush();
     output.close();
    } else if (source.isDirectory()) { // 如果是文件夹 递归读取子文件或文件夹
    
     File[] file = source.listFiles();
     for (int i = 0; i < file.length; i++) {
      if(file[i].isDirectory())
       copyDirectiory(sourceFile + "/" + file[i].getName(),
        desFile + "/" + file[i].getName());
      else{
       copyDirectiory(sourceFile + "/" + file[i].getName(),
         desFile + "/");
      }
     }
    
    }
    return true;
   } catch (Exception e) {
    e.printStackTrace();
    return false;
   } finally {
    if (input != null)
     input.close();
    if (output != null)
     output.close();
   }
}
/**
* 刪除文件或文件夾
* @param file
*/
public static void deleteFile(File file){ 
     if (file.exists()){ 
      if(file.isFile()){ 
       file.delete(); 
      }else if(file.isDirectory()){ 
       File files[] = file.listFiles(); 
       for(int i=0;i<files.length;i++){ 
        deleteFile(files[i]); 
       } 
      } 
      file.delete(); 
     }else{ 
      System.out.println("所删除的文件不存在!"+'\n'); 
     } 
   }


}

第二个类BatchJar :

package com.jar;

import java.io.File;
/**
* 批处理:在指定文件夹中的所有Jar文件中添加文件或文件夹
* @author zhang
*
*/

public class BatchJar {

/**
* @param args
*/
public static void main(String[] args) {
   // TODO Auto-generated method stub
   BatchJar jar = new BatchJar();
   jar.batchJar("D:/temp/疯狂农场", "jar", "D:/temp/ashinanren.jar");
}
public void batchJar(String dir, String fileType, String fileName){
   System.out.println(fileName+" 即将被添加到"+dir+"中的"+fileType+"文件中..");
   batchRar(dir,fileType,fileName);
   System.out.println("添加完成!");
}
/**

* @param dir
*            需要遍历的文件夹
* @param fileType
*            压缩文件类型 rar jar zip
* @param fileName
*            要添加的文件或文件夹

*            遍历文件夹 拼写批处理命令
*/
JARDemo jar = new JARDemo();
public void batchRar(String dir, String fileType, String fileName) {

   File file = new File(dir);
   if (file.exists()) {
    if (file.isFile()) { //
     if (isType(file, fileType)) {
      
      jar.fileAddToJar(fileName, file.getAbsolutePath());    
     }

    } else if (file.isDirectory()) {
     File files[] = file.listFiles();
     for (int i = 0; i < files.length; i++) {
      batchRar(files[i].getAbsolutePath(), fileType, fileName);
     }
    }
    // file.delete();
   } else {
    System.out.println("所删除的文件不存在!" + '\n');
   }
  

}
/**
* 判断是否为指定文件类型
*/
private boolean isType(File file, String fileType) {
   if (file == null) {
    return false;
   }
   String fileName = file.getAbsolutePath();
   String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
   // System.out.println("====后缀:"+suffix);
   if (fileType.equals(suffix)) {
    return true;
   }
   return false;
}
}

第三个类JARDemo :
package com.jar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
* 压缩指定文件夹
* 解压指定压缩文件
* 把指定源文件或文件夹添加到指定压缩包中
* @author zhang
*
*/

public class JARDemo {
public static void main(String[] args) {
   JARDemo t = new JARDemo();

   t.fileAddToJar("d:/com", "d:/temp/shinanren.jar");
}

/**
* 把指定源文件添加到指定压缩包中

* @param sourceFileName
*            要压缩到指定目标压缩文件的源文件或文件夹
* @param destFileName
*            目标压缩文件
* @throws IOException
*/
public void fileAddToJar(String sourceFileName, String jarName) {
//   System.out.println("**=="+sourceFileName);
   // 先解压到临时文件夹,存在先刪除 不存在直接創建
   String tempFileName = "c:/temp";
   File tempDir = new File(tempFileName);
   try {

    if (tempDir.exists()) {
     FolderCopy.deleteFile(tempDir);// 刪除文件夾
    } else {
     tempDir.mkdirs();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }

   try {
    this.unJar(jarName, tempFileName);// 先解压目标压缩Jar文件 到临时文件夹
    File f = new File(sourceFileName);
   
    if(f.isDirectory()){//如果是文件夹
     FolderCopy.copyDirectiory(sourceFileName, tempFileName+"/"+new File(sourceFileName).getName());// 拷贝源文件到临时文件夹
    
    }
    if(f.isFile())
     FolderCopy.copyDirectiory(sourceFileName, tempFileName);// 拷贝源文件到临时文件夹

    this.jar(tempFileName, jarName);// 再压缩临时文件夹

    FolderCopy.deleteFile(tempDir); //再删除临时文件夹

   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

}

/**
* 压缩指定文件夹

* @param souceFileName
*            源文件
* @param destFileName
*            目标文件
*/
private void jar(String souceFileName, String destFileName) {
   destName = destFileName;
   File file = new File(souceFileName);
   try {
    jar(file, destFileName);
   } catch (Exception e) {
    e.printStackTrace();
   }
}

private void jar(File souceFile, String destFileName) throws IOException {
   FileOutputStream fileOut = null;
   try {
    fileOut = new FileOutputStream(destFileName);
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }
   JarOutputStream out = new JarOutputStream(fileOut);
   jar(souceFile, out, "");
   out.close();
}

String destName = "";

private void jar(File souceFile, JarOutputStream out, String base)
    throws IOException {

   if (souceFile.isDirectory()) {
    File[] files = souceFile.listFiles();
    out.putNextEntry(new JarEntry(base + "/"));
    base = base.length() == 0 ? "" : base + "/";
    for (File file : files) {
     jar(file, out, base + file.getName());
    }
   } else {
    if (base.length() > 0) {
     out.putNextEntry(new JarEntry(base));
    } else {
     out.putNextEntry(new JarEntry(souceFile.getName()));
    }

    FileInputStream in = new FileInputStream(souceFile);

    int b;
    byte[] by = new byte[1024];
    while ((b = in.read(by)) != -1) {
     out.write(by, 0, b);
    }
    in.close();
   }
}

/**
* 解压缩文件

* @param zipFilename
* @param outputDirectory
* @throws IOException
*/
public synchronized void unJar(String jarFilename, String outputDirectory)
    throws IOException {
   File outFile = new File(outputDirectory);
   if (!outFile.exists()) {
    outFile.mkdirs();
   }

   JarFile jarFile = new JarFile(jarFilename);
   Enumeration en = jarFile.entries();
   JarEntry jarEntry = null;
   while (en.hasMoreElements()) {
    jarEntry = (JarEntry) en.nextElement();
    if (jarEntry.isDirectory()) {
     // mkdir directory
     String dirName = jarEntry.getName();
     dirName = dirName.substring(0, dirName.length() - 1);

     File f = new File(outFile.getPath() + File.separator + dirName);
//    

    } else {
     // unjar file
     File f = new File(outFile.getPath() + File.separator
       + jarEntry.getName());
    
     this.createFile(f);

     InputStream in = jarFile.getInputStream(jarEntry);
     FileOutputStream out = new FileOutputStream(f);
     try {
      int c;
      byte[] by = new byte[1024];
      while ((c = in.read(by)) != -1) {
       out.write(by, 0, c);
      }
      // out.flush();
     } catch (IOException e) {
      e.printStackTrace();
     } finally {
      out.close();
      in.close();
     }
    }
   }
}

/**
* 创建文件 包含不存在的文件夹
*/
public boolean createFile(File file) {
//   System.out.println("=="+file.getAbsolutePath());
   if (file == null)
    return false;
   try {
    if (file.isDirectory()&&!file.exists()) {
     file.mkdirs();// 创建目录
    } else { 
    
     File fileP = new File(file.getParent());
     if(!fileP.exists()){
      fileP.mkdirs();
     }
    
    }
    file.createNewFile();//先确保创建文件夹目录后创建文件
    return true;
   } catch (Exception e) {
    e.printStackTrace();
    return false;
   }
}

/**
* 把指定文件打包 只能是文件不能文件夹
*/
public void fileJar() {
   String[] filenames = new String[] { "d:/d.jar", "d:/a.txt" };
   byte[] buf = new byte[1024];
   try {
    // Create the Jar file
    String outFilename = "d:/d.jar";
    JarOutputStream out = new JarOutputStream(new FileOutputStream(
      outFilename));

    for (int i = 0; i < filenames.length; i++) {
     FileInputStream in = new FileInputStream(filenames[i]);

     // Add Jar entry to output stream.
     System.out.println("==" + filenames[i]);
     out.putNextEntry(new JarEntry(filenames[i]));

     // Transfer bytes from the file to the Jar file
     int len;
     while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
     }

     // Complete the entry

     out.closeEntry();
     in.close();
    }

    // Complete the Jar file
    out.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
}
}

posted on 2010-11-19 10:57 Daniel 阅读(907) 评论(0)  编辑  收藏 所属分类: CoreJava

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(3)

随笔档案

文章分类

文章档案

相册

搜索

  •  

最新评论