JavaSE ZIp压缩和解压

ZIP压缩输入流/输出流

(1)ZipEntry

此类用于表示ZIP文件条目。
构造方法

ZipEntry(String name)   //创建具有指定名称的新的zip条目。  
ZipEntry(ZipEntry e)   //创建一个新的zip条目,其中的字段从指定的zip条目中取出。  

常用方法

方法返回值说明
isDirectory()boolean如果这是目录条目,则返回true。
getName()String返回条目的名称。
(1)压缩文件

利用ZipOutputStream类对象,可将文件压缩成.zip文件
构造方法

ZipOutputStream(OutputStream out)

ZipOutputStream常用方法

方法返回值说明
putNextEntryvoid开始写一个新的ZipEntry,并将流定位到条目数据的开头。
write(byte[] b,int off,int len)void将一个字节数组写入当前的ZIP条目数据
finish()void完成编写ZIP输出流的内容,而不关闭底层流OutputStream。
setComment(String comment)void设置ZIP文件注释。
压缩E盘的hello文件夹,该文件夹下有hello1.txt和hello2.txt,将压缩后的hello.zip放在E盘根目录下
这个只能压缩文件夹里不包含文件夹的,即文件夹下只有两个文档的文件夹,因为这里面重复建文件夹了

完整压缩与解压在最后

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ToZip {
    private void zip(String zipFilename, File inputfile) throws Exception{
        FileOutputStream file=new FileOutputStream(zipFilename);
        ZipOutputStream zipout=new ZipOutputStream(file);
        zip(zipout,inputfile,"");
        System.out.println("压缩中");
        zipout.close();
    }
    private void zip(ZipOutputStream zipout,File file,String base) throws Exception{
          if(file.isDirectory()){   //看是否为一个目录
              File[] files=file.listFiles();
              if(base.length()!=0){
                  System.out.println(base);
                  zipout.putNextEntry(new ZipEntry(base+"/"));
              }
              for(int i=0;i<files.length;i++){
                  zip(zipout,files[i],base+files[i]);
              }
          }else{
              zipout.putNextEntry(new ZipEntry(base));
              FileInputStream in=new FileInputStream(file);
              int b;
              System.out.println(base);
              while((b=in.read())!=-1){   //读入一个字节的数据
                  zipout.write(b);
              }
              in.close();
          }
    }
    public static void main(String[] args) {
        ToZip z=new ToZip();
        try {
            z.zip("E:/myzip.zip",new File("E:/hello"));
            System.out.println("压缩完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

(2)ZipInputStream

构造方法

ZipInputStream(InputStream in)   //创建一个新的ZIP输入流。 
ZipInputStream(InputStream in, Charset charset)   //创建一个新的ZIP输入流。 
方法返回值说明
read(byte[] b, int off, int len)int从当前ZIP条目读取到字节数组。
getNextEntry()ZipEntry读取下一个ZIP文件条目,并将流定位在条目数据的开头。
createZipEntry(String name)protected ZipEntry为指定的条目名称创建一个新的 ZipEntry对象。
skip(long n)long跳过当前ZIP条目中指定的字节数。
available()intEOF到达当前条目数据后返回0,否则返回1。
closeEntry()void关闭当前的ZIP条目,并定位流以读取下一个条目。
close()void关闭此输入流并释放与流相关联的任何系统资源

压缩和解压完整代码

package com.pkg;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import static com.pkg.ZipUtils.compress;

public class ZipTransfrom {
    private static final String ZIP_POSTFIX="zip";

    private File FileByZip(String zipFile){
        int indexExceptZip=FileNameByZip(zipFile);
         String file=zipFile.substring(0,indexExceptZip);
         return new File(file);  //新建一个去掉zip后缀的文件
    }
    private int FileNameByZip(String zipFile){
        int last=zipFile.lastIndexOf(".");    //获得zip后缀前的.的位置
        if(last==-1)
            throw new RuntimeException(zipFile+"is not Zip format !(不是Zip文件名格式)");
         String format=zipFile.substring(last+1);   //获取文件后缀
         if(!ZIP_POSTFIX.equalsIgnoreCase(format))
             throw new RuntimeException(zipFile+"is not Zip format !(不是Zip文件名格式)");
         return last;
    }
    /*
     *     compress(String zipFile,List<File> fileList)
     *    由主函数调用
     *    zipFile:建立的zip文件的路径(带有后缀.zip)
     *     fileList:待压缩的文件集合
     */
    public File compress(String zipFile,List<File> fileList){
        return compress(zipFile,fileList,true);
    }
    /*
     *       compress(String zipFile,List<File> fileList,boolean isDelete)
     *      由 compress(String zipFile,List<File> fileList)调用 目的让主函数的调用默认删除原来的压缩包
     *      zipFile:压缩文件名路径 (带有后缀.zip)
     *      filList:待压缩文件集合
     *      isDelete:如果出现同名压缩包, 是否删除原本的压缩包, 如果false,且出现同名则抛异常
     */
    public File compress(String zipFile,List<File> fileList,boolean isDelete){
            File f=FileByZip(zipFile);    //获取zip的文件(去除.zip)
            return compress(f.getName(),f.getParent(),getFilePathArray(fileList),false,true);
    }
    public String[] getFilePathArray(List<File> fileList){
        String[] strs=new String[fileList.size()];
        for(int index=0;index<strs.length;index++)
            strs[index]=fileList.get(index).getPath();
        return strs;
    }
    /*
         compress(String zipName,String zipFilePath,String[] filePaths,boolean isNewFolde,boolean isDelete)
         zipName:压缩文件名(无后缀.zip)
         zipFilePath:压缩路径
         filePaths:待压缩文件的路径
         isNewFolder:是否在压缩包新建同名文件夹
         isDelete:如果出现同名压缩包, 是否删除原本的压缩包, 如果false,且出现同名则抛异常
     */
    public File compress(String zipName,String zipFilePath,String[] filePaths,boolean isNewFolder,boolean isDelete){
        File target=null;
        File source=new File(zipFilePath);
        if(source.exists()){
            String base=isNewFolder?zipName+File.separator:"";
            zipName=zipName+"."+ZIP_POSTFIX;  //之前去掉zip是为了判断输入的是不是zip后缀
            target=new File(source.getPath(),zipName);  //从父路径名字符串和子路径名字符串创建新的 File实例。
            if(target.exists()){
                if(!isDelete)
                    throw new RuntimeException("压缩包重名");
                target.delete();
            }
            FileOutputStream fout=null;
            ZipOutputStream zout=null;
            try {
                fout=new FileOutputStream(target);
                zout=new ZipOutputStream(fout);
                for (String flip:filePaths) {
                    addEntry(base,new File(flip),zout);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                if(zout!=null){
                    try {
                        zout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fout!=null){
                    try {
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return target;
    }
    private void addEntry(String base,File source,ZipOutputStream zipStream){
        String entry=base.concat(source.getName());//将指定的字符串连接到末尾
        if(source.isDirectory()){
            for(File file:source.listFiles())
                addEntry(entry+File.separator,file,zipStream);
        }else{
                FileInputStream fin=null;
                BufferedInputStream  bin=null;
                byte[] buffer=new byte[1024*10];
            try {
                fin=new FileInputStream(source);
                bin=new BufferedInputStream(fin,buffer.length);
                zipStream.putNextEntry(new ZipEntry(entry));
                int read=0;
                while((read=bin.read(buffer,0,buffer.length))!=-1){
                    zipStream.write(buffer,0,read);
                }
                zipStream.closeEntry();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(bin!=null){
                    try {
                        bin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }if(fin!=null){
                    try {
                        fin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
	/*
		decompression(String ZipFilePath,String source)
		ZipFilePath:要解压的zip路径
		souce:要解压到的路径
	*/
    public void decompression(String ZipFilePath,String source){
        File file=new File(ZipFilePath);
        if(file.exists()) {
            ZipInputStream zin = null;
            BufferedOutputStream bout = null;
            try {
                zin = new ZipInputStream(new FileInputStream(file));
                ZipEntry zipEntry = null;
                while ((zipEntry = zin.getNextEntry()) != null && !zipEntry.isDirectory()) {
                   // System.out.println(targetStr+": "+entry.getName());
                    File target = new File(source, zipEntry.getName());
                    if (!target.getParentFile().exists()) {
                        target.getParentFile().mkdirs();
                    }
                    // System.out.println("parent: "+target.getParentFile().getName());
                    //System.out.println("target: "+target.getName());
                    bout = new BufferedOutputStream(new FileOutputStream(target));
                    int read = 0;
                    byte[] buffer = new byte[1024 * 10];
                    while ((read = zin.read(buffer, 0, buffer.length)) != -1) {
                        bout.write(buffer, 0, read);
                    }
                    bout.flush();
                }
                zin.closeEntry();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e){
                throw new RuntimeException(e);
            } finally {
                if (zin != null) {
                    try {
                        zin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bout != null) {
                    try {
                        bout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        ZipTransfrom zip=new ZipTransfrom();
        String src="E://hello";
        List<File> fileList= Arrays.asList(new File(src).listFiles());
        zip.compress("E://TEST.zip",fileList);  //压缩
        zip.decompression("E://TEST.zip","E://EEEEEEE");//解压
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值