`

java文件打包压缩

    博客分类:
  • java
 
阅读更多
import java.io.*; 
import java.util.jar.*; 
public class testpackage { 
protected static byte buf[] = new byte[1024]; 
  
/** 
  * 遍历目录并添加文件. 
  * @param jos - JAR 输出流 
  * @param file - 目录文件名 
  * @param pathName - ZIP中的目录名 
  * @throws IOException 
  * @throws FileNotFoundException 
  */ 
private static void recurseFiles(JarOutputStream jos, File file, String pathName) 
  throws IOException, FileNotFoundException 
{ 
  if (file.isDirectory()) 
  { 
   pathName = pathName + file.getName() + "/"; 
   jos.putNextEntry(new JarEntry(pathName)); 
   String fileNames[] = file.list(); 
   if (fileNames != null) 
   { 
    for (int i = 0; i = 0)  
    jos.write(buf, 0, len); 
   in.close(); 
   jos.closeEntry(); 
  } 
} 
  
/** 
  * 创建 ZIP/JAR 文件. 
  * @param directory - 要添加的目录 
  * @param zipFile - 保存的 ZIP 文件名 
  * @param zipFolderName - ZIP 中的路径名 
  * @param level - 压缩级别(0~9) 
  * @throws IOException 
  * @throws FileNotFoundException 
  */ 
public static void makeDirectoryToZip(File directory, File zipFile, String zipFolderName, int level) 
  throws IOException, FileNotFoundException 
{ 
  level = checkZipLevel(level); 
   
  if(zipFolderName == null) { 
   zipFolderName = ""; 
  } 
   
  JarOutputStream jos = new JarOutputStream(new FileOutputStream(zipFile), new Manifest()); 
  jos.setLevel(level); 
   
  String fileNames[] = directory.list(); 
  if (fileNames != null) 
  { 
   for (int i = 0; i  9) level = 7; 
  return level; 
} 
} 


jsp页面中调用

    <%
String homeDir = "/home/wenqx/work/workspace/qzt3474/";
java.io.File zipFile = new java.io.File(homeDir, "download" + java.io.File.separatorChar
 + "test_pages.zip");
java.io.File pagesDirectory = new java.io.File(homeDir, "testt");
out.println("Making zip file from folder /test to " + zipFile);
out.println("<br/>");
com.zip.testPackage.makeDirectoryToZip(pagesDirectory, zipFile, null, 9);
out.println("Zip file " + zipFile + " has been made.");
%>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics