java 导入zip项目_[导入]利用JAVA打包生成zip文件的类

package com.order;

import java.io.*;

import java.util.List;

import org.apache.tools.zip.*;

/**

* 把多个文件打包到一个文件

* @author xiaofei.hu

*

*/

public class ZipUtil {

public static void toZip(File[] files, File zipFile){

}

/**

* The buffer.

*/

protected static byte buf[] = new byte[1024];

/**

* 遍历目录并添加文件.

* @param jos - JAR 输出流

* @param file - 目录文件名

* @param pathName - ZIP中的目录名

* @throws IOException

* @throws FileNotFoundException

*/

private static void recurseFiles(ZipOutputStream jos, File file, String pathName)

throws IOException, FileNotFoundException

{

if (file.isDirectory())

{

pathName = pathName + file.getName() + "/";

jos.putNextEntry(new ZipEntry(pathName));

String fileNames[] = file.list();

if (fileNames != null)

{

for (int i = 0; i < fileNames.length; i++)

recurseFiles(jos, new File(file, fileNames[i]), pathName);

}

} else

{

ZipEntry jarEntry = new ZipEntry(pathName + file.getName());

//                System.out.println(pathName + "  " + file.getName());

FileInputStream fin = new FileInputStream(file);

BufferedInputStream in = new BufferedInputStream(fin);

jos.putNextEntry(jarEntry);

int len;

while ((len = in.read(buf)) >= 0)

jos.write(buf, 0, len);

in.close();

jos.closeEntry();

}

}

public static void toZip(List files, File zipFile, String zipFolderName, int level)

throws IOException, FileNotFoundException

{

level = checkZipLevel(level);

if(zipFolderName == null) {

zipFolderName = "";

}

ZipOutputStream jos = new ZipOutputStream(new FileOutputStream(zipFile));

jos.setLevel(level);

for (int i = 0; i < files.size(); i++){

recurseFiles(jos, files.get(i), files.get(i).getPath());

}

jos.close();

}

/**

* 创建 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 = "";

}

ZipOutputStream jos = new ZipOutputStream(new FileOutputStream(zipFile));

jos.setLevel(level);

String fileNames[] = directory.list();

if (fileNames != null)

{

for (int i = 0; i < fileNames.length; i++)

recurseFiles(jos, new File(directory, fileNames[i]), zipFolderName);

}

jos.close();

}

/**

* 检查并设置有效的压缩级别.

* @param level - 压缩级别

* @return 有效的压缩级别或者默认压缩级别

*/

public static int checkZipLevel(int level)

{

if(level < 0 || level > 9) level = 7;

return level;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值