java实现 zip压缩文件 三种方法

网上查了许久,最后发现三种不错的方法:

一般用第一种JDK自带的方法,不要使用中文文件名称就可以了。


1、jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,

出现乱码问题,实现代码如下:

/**
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
* @param sourceDir 如果是目录,eg:D:\\MyEclipse\\first\\testFile,则压缩目录下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,则只压缩本文件
* @param zipFile 最后压缩的文件路径和名称,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath)
throws IOException {

File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 创建写出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);

String basePath = null;

// 获取目录
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}

zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}

return zipFile;
}

/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}

InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}

}

2、使用org.apache.tools.zip.ZipOutputStream,代码如下,

Java代码:
  1. packagenet.szh.zip;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.File;
  4. importjava.io.FileInputStream;
  5. importjava.io.FileOutputStream;
  6. importjava.util.zip.CRC32;
  7. importjava.util.zip.CheckedOutputStream;
  8. importorg.apache.tools.zip.ZipEntry;
  9. importorg.apache.tools.zip.ZipOutputStream;
  10. publicclassZipCompressor{
  11. staticfinalintBUFFER=8192;
  12. privateFilezipFile;
  13. publicZipCompressor(StringpathName){
  14. zipFile=newFile(pathName);
  15. }
  16. publicvoidcompress(StringsrcPathName){
  17. Filefile=newFile(srcPathName);
  18. if(!file.exists())
  19. thrownewRuntimeException(srcPathName+"不存在!");
  20. try{
  21. FileOutputStreamfileOutputStream=newFileOutputStream(zipFile);
  22. CheckedOutputStreamcos=newCheckedOutputStream(fileOutputStream,
  23. newCRC32());
  24. ZipOutputStreamout=newZipOutputStream(cos);
  25. Stringbasedir="";
  26. compress(file,out,basedir);
  27. out.close();
  28. }catch(Exceptione){
  29. thrownewRuntimeException(e);
  30. }
  31. }
  32. privatevoidcompress(Filefile,ZipOutputStreamout,Stringbasedir){
  33. /*判断是目录还是文件*/
  34. if(file.isDirectory()){
  35. System.out.println("压缩:"+basedir+file.getName());
  36. this.compressDirectory(file,out,basedir);
  37. }else{
  38. System.out.println("压缩:"+basedir+file.getName());
  39. this.compressFile(file,out,basedir);
  40. }
  41. }
  42. /**压缩一个目录*/
  43. privatevoidcompressDirectory(Filedir,ZipOutputStreamout,Stringbasedir){
  44. if(!dir.exists())
  45. return;
  46. File[]files=dir.listFiles();
  47. for(inti=0;i<files.length;i++){
  48. /*递归*/
  49. compress(files[i],out,basedir+dir.getName()+"/");
  50. }
  51. }
  52. /**压缩一个文件*/
  53. privatevoidcompressFile(Filefile,ZipOutputStreamout,Stringbasedir){
  54. if(!file.exists()){
  55. return;
  56. }
  57. try{
  58. BufferedInputStreambis=newBufferedInputStream(
  59. newFileInputStream(file));
  60. ZipEntryentry=newZipEntry(basedir+file.getName());
  61. out.putNextEntry(entry);
  62. intcount;
  63. bytedata[]=newbyte[BUFFER];
  64. while((count=bis.read(data,0,BUFFER))!=-1){
  65. out.write(data,0,count);
  66. }
  67. bis.close();
  68. }catch(Exceptione){
  69. thrownewRuntimeException(e);
  70. }
  71. }
  72. }

3、 可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。
Java代码
  1. packagenet.szh.zip;
  2. importjava.io.File;
  3. importorg.apache.tools.ant.Project;
  4. importorg.apache.tools.ant.taskdefs.Zip;
  5. importorg.apache.tools.ant.types.FileSet;
  6. publicclassZipCompressorByAnt{
  7. privateFilezipFile;
  8. publicZipCompressorByAnt(StringpathName){
  9. zipFile=newFile(pathName);
  10. }
  11. publicvoidcompress(StringsrcPathName){
  12. Filesrcdir=newFile(srcPathName);
  13. if(!srcdir.exists())
  14. thrownewRuntimeException(srcPathName+"不存在!");
  15. Projectprj=newProject();
  16. Zipzip=newZip();
  17. zip.setProject(prj);
  18. zip.setDestFile(zipFile);
  19. FileSetfileSet=newFileSet();
  20. fileSet.setProject(prj);
  21. fileSet.setDir(srcdir);
  22. //fileSet.setIncludes("**/*.java");包括哪些文件或文件夹eg:zip.setIncludes("*.java");
  23. //fileSet.setExcludes(...);排除哪些文件或文件夹
  24. zip.addFileset(fileSet);
  25. zip.execute();
  26. }
  27. }
测试一下
Java代码
  1. packagenet.szh.zip;
  2. publicclassTestZip{
  3. publicstaticvoidmain(String[]args){
  4. ZipCompressorzc=newZipCompressor("E:\\szhzip.zip");
  5. zc.compress("E:\\test");
  6. ZipCompressorByAntzca=newZipCompressorByAnt("E:\\szhzipant.zip");
  7. zca.compress("E:\\test");
  8. }
  9. }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值