Java压缩文件和解压缩文件

来源:互联网 发布:小学语文教学软件 编辑:程序博客网 时间:2024/05/16 00:28
<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
原创粉丝点击