欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java自动解压文件实例代码

程序员文章站 2023-12-14 17:09:04
复制代码 代码如下:import java.io.file; import java.io.fileoutputstream; import java.io.ioexcep...

复制代码 代码如下:

import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.util.enumeration;
import java.util.zip.zipentry;
import java.util.zip.zipfile;


public class unzipper {

    /**
     * 解压文件到当前目录 功能相当于右键 选择解压
     * @param zipfile
     * @param
     * @author gabriel
     */
    @suppresswarnings("rawtypes")
    public static void unzipfiles(file zipfile)throws ioexception{
        //得到压缩文件所在目录
        string path=zipfile.getabsolutepath();
        path=path.substring(0,path.lastindexof("\\"));
       // system.out.println("path "+path);
        zipfile zip = new zipfile(zipfile);
        for(enumeration entries =zip.entries();
                entries.hasmoreelements();){
            zipentry entry = (zipentry)entries.nextelement();
            string zipentryname = entry.getname();
            inputstream in = zip.getinputstream(entry);
            //outpath输出目录
            string outpath = (path+"\\"+zipentryname).replaceall("\\*", "/");;
            //system.out.println("outpath "+outpath);
            //判断路径是否存在,不存在则创建文件路径
            file file = new file(outpath.substring(0, outpath.lastindexof('/')));
            if(!file.exists()){
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if(new file(outpath).isdirectory()){
                continue;
            }
            //输出文件路径信息
            system.out.println(outpath);

            outputstream out = new fileoutputstream(outpath);
            byte[] buf1 = new byte[1024];
            int len;
            while((len=in.read(buf1))>0){
                out.write(buf1,0,len);
            }
            in.close();
            out.close();
            }
        system.out.println("******************解压完毕********************");
    }

   
    public static void main(string[] args) {
        try {
            unzipfiles(new file("d:\\all\\zip\\default.adiumemoticonset.zip"));
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }
}

上一篇:

下一篇: