Java压缩文件和解压缩文件

<span style="font-size:18px;">//压缩数据文件
	            String uploadZipFileName=UUID.randomUUID().toString()+".zip";
	            String zipFilePath=descPath+File.separator+uploadZipFileName;
	            File zipFile = new File(zipFilePath);
	            if(!zipFile.exists()){
	            	zipFile.createNewFile();
	            }
	            OutputStream os =new FileOutputStream(zipFile);
	            BufferedOutputStream bos = new BufferedOutputStream(os);
	            ZipOutputStream zos = new ZipOutputStream(bos);
	            setFileToZip(desFile, zos, "");//存放到压缩包的根路径
	            zos.flush();
	            zos.close();
	            bos.close();
	            os.close();

/**
     * 将文件放入zip中
     * @param file
     * @param base
     */
    private void setFileToZip(File file,ZipOutputStream zos,String base){
        try{
            ZipEntry entry = new ZipEntry(base+"/"+file.getName());
            zos.putNextEntry(entry);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] b = new byte[1024];
            while (bis.read(b, 0, 1024) != -1) {
                zos.write(b, 0, 1024);
            }
            bis.close();
            zos.closeEntry();
        } catch (Exception e){
            e.printStackTrace();
        }
    }



/**
     *解压缩回传的数据文件
     *@param
     *@return
     */
    private void unZipFile(String srcZipFile,String descPath){
         File descFile = new File(descPath);
         if(descFile.isDirectory() && !descFile.exists()){
             descFile.mkdirs();
         }
         
         try {
             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcZipFile));
             ZipInputStream zis = new ZipInputStream(bis);
             BufferedOutputStream bos = null;
             
             java.util.zip.ZipEntry entry = null;
             while ((entry=zis.getNextEntry()) != null) {
                 if(entry.isDirectory()){
                     continue;
                 }
                 String entryName = entry.getName();
                 bos = new BufferedOutputStream(new FileOutputStream(descPath+"/"+entryName));
                 byte [] buffer=new byte[512];
                 while (zis.read(buffer)!=-1) {
                      bos.write(buffer);
                 }
                 bos.flush();
                 bos.close();
             }
             bis.close();
             zis.close();
         }catch(Exception ex){
             ex.printStackTrace();
         }
    }
</span>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值