针对格式为tar.gz与zip格式的压缩包根据压缩包流进行的解压、指定包内文件预览等等功能案例

目录

一、解压zip

二、解压tar.gz

三、解压zip压缩包流中指定目录的文件内容并预览

四、解压tar.gz压缩包流中指定目录的文件内容并预览

五、预览文件内容乱码处理


总结tar.gz与zip压缩包操作,根据压缩包流进行一系列加压,获取压缩包文件中指定文件的内容并预览操作。

一、解压zip

根据获取的压缩包文件流,解压压缩包  文件格式为zip

  /**
     * 解压zip指定目录的日志文件内容
     *
     * @param getObjectRequest 件对象p要解压的zi文  压缩包输入流,根据自己情况传压缩包流
     * @param filePath         文件目录名称  
     * @throws IOException
     */
public void getLogZipFlows(String filePath, GetObjectRequest getObjectRequest) {
        ZipFile zipFile = null;
        File file = new File(zipFilePath);
        cosClientService.getCOSClient().getObject(getObjectRequest, file);
        try {
            Charset CP866 = Charset.forName("CP866");
            //在给定指定的File对象的情况下打开ZIP文件以进行读取
            zipFile = new ZipFile(file, CP866);
            createDirectory(folderPathZip, null);//创建输出目录
            //返回ZIP文件条目的枚举。
            Enumeration<?> enums = zipFile.entries();
            if (null != enums) {
                while (enums.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) enums.nextElement();
                    if (entry.isDirectory()) {//是目录
                        createDirectory(folderPathZip, entry.getName());//创建空目录
                    } else {//是文件
                        File tmpFile = new File(folderPathZip + "/" + entry.getName());
                        createDirectory(tmpFile.getParent() + "/", null);//创建输出目录
                        InputStream in = null;
                        OutputStream out = null;
                        try {
                            //返回用于读取指定zip文件条目内容的输入流。
                            in = zipFile.getInputStream(entry);
                            out = new FileOutputStream(tmpFile);
                            int length = 0;
                            byte[] b = new byte[2048];
                            while ((length = in.read(b)) != -1) {
                                out.write(b, 0, length);
                            }
                        } catch (IOException ex) {
                            throw ex;
                        } finally {
                            if (in != null)
                                in.close();
                            if (out != null)
                                out.close();
                        }
                    }
                }
            }
        } catch (CosServiceException cs) {
            logger.error("下载文件" + filePath + "失败");
            cs.printStackTrace();
            throw new BadRequestException("error.params.fileNameNotExist");
        } catch (CosClientException cc) {
            cc.printStackTrace();
            throw new BadRequestException("error.params.clientException");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            cosClientService.getCOSClient().shutdown();
           /* deleteZip(zipFilePath);
            deleteZip(folderPathZip);*/
        }

    }

二、解压tar.gz

根据获取的压缩包文件流,解压压缩包  文件格式为tar.gz

 /**
     *解压tar.gz指定目录的日志文件内容
     *
     * @param getObjectRequest 件对象p要解压的zi文  压缩包输入流,根据自己情况传压缩包流
     * @param filePath        
     * @throws IOException
     */
    public byte[] getLogGzFlows(String filePath, GetObjectRequest getObjectRequest) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        GZIPInputStream gzis = null;
        TarArchiveInputStream tais = null;
        OutputStream out = null;
        try {
            //要解压到某个指定的目录下
            File file = new File(tarGzFilePath);
            cosClientService.getCOSClient().getObject(getObjectRequest, file);
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            gzis = new GZIPInputStream(bis);
            tais = new TarArchiveInputStream(gzis);
            TarArchiveEntry tae = null;
            boolean flag = false;
            while ((tae = tais.getNextTarEntry()) != null) {
                File tmpFile = new File(folderPathTarGz + "/" + tae.getName());
                if (!flag) {
                    //使用 mkdirs 可避免因文件路径过多而导致的文件找不到的异常
                    new File(tmpFile.getParent()).mkdirs();
                    flag = true;
                }
                out = new FileOutputStream(tmpFile);
                int length = 0;
                byte[] b = new byte[1048576];
                while ((length = tais.read(b)) != -1) {
                    out.write(b, 0, length);
                }
            }
        } catch (CosServiceException cs) {
            logger.error("下载文件" + filePath + "失败");
            cs.printStackTrace();
            throw new BadRequestException("error.params.fileNameNotExist");
        } catch (CosClientException cc) {
            cc.printStackTrace();
            throw new BadRequestException("error.params.clientException");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (tais != null) tais.close();
                if (gzis != null) gzis.close();
                if (bis != null) bis.close();
                if (fis != null) fis.close();
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 

三、解压zip压缩包流中指定目录的文件内容并预览

    /**
     * 解压zip指定目录的文件内容
     *
     * @param getObjectRequest 件对象p要解压的zi文  压缩包输入流
     * @param filePath         文件目录名称  压缩包中某个文件的目录名
     * @throws IOException
     */
    public byte[] getLogZipFlows(String filePath, GetObjectRequest getObjectRequest) {
        ZipInputStream zipis = null;
        COSObjectInputStream cosObjectInput = null;
        ByteArrayOutputStream output = null;
        try {
            COSObject cosObject = cosClientService.getCOSClient().getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
            zipis = new ZipInputStream(cosObjectInput, Charset.forName("GBK"));
            ZipEntry fentry = null;
            byte[] logs = null;
            while ((fentry = zipis.getNextEntry()) != null) {
                if (fentry.getSize() > 0 && (filePath.equals(fentry.getName()) || "first".equals(filePath))) {
                    output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[zipis.available()];
                    int n = 0;
                    while ((n = zipis.read(buffer)) != -1) {
                        output.write(buffer, 0, n);
                    }
                    logs = output.toByteArray();
                    return fileTypeDecode(logs);
                }
            }
        } catch (CosServiceException cs) {
          
            throw new BadRequestException("error.params.fileNameNotExist");
        } catch (CosClientException cc) {
          
            throw new BadRequestException("error.params.clientException");
        } catch (Exception e) {
            
            throw new BadRequestException("error.params.getZIPFileDirectoryFailure");
        } finally {
            try {
                if (cosObjectInput != null)
                    cosObjectInput.close();
                if (zipis != null)
                    zipis.close();
                if (output != null) {
                    output.flush();
                    output.close();
                }
                cosClientService.getCOSClient().shutdown();
            } catch (IOException e) {
                logger.error("获取压缩包中所有文件目录时关闭输入输出流失败!错误描述:" + e.getMessage());
            }
        }
        return null;
    }

 

四、解压tar.gz压缩包流中指定目录的文件内容并预览

/**
     * 解压tar.gz指定目录名的文件内容
     *
     * @param getObjectRequest 要解压的tar.gz文件对象 压缩包输入流
     * @param filePath         文件目录名称  压缩包中某个文件的目录名
     * @throws IOException
     */
    public byte[] getLogGzFlows(String filePath, GetObjectRequest getObjectRequest) {
        BufferedInputStream bis = null;
        GZIPInputStream gzis = null;
        TarArchiveInputStream tais = null;
        COSObjectInputStream cosObjectInput = null;
        ByteArrayOutputStream out = null;
        try {
            //要解压到某个指定的目录下
            COSObject cosObject = cosClientService.getCOSClient().getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
            bis = new BufferedInputStream(cosObjectInput);
            gzis = new GZIPInputStream(bis);
            tais = new TarArchiveInputStream(gzis);
            TarArchiveEntry tae = null;
            byte[] gzLog = null;
            while ((tae = tais.getNextTarEntry()) != null) {
                if (filePath.equals(tae.getName()) || "first".equals(filePath)) {
                    out = new ByteArrayOutputStream();
                    byte[] buffer = new byte[tais.available()];
                    int n = 0;
                    while (-1 != (n = tais.read(buffer))) {
                        out.write(buffer, 0, n);
                    }
                    gzLog = out.toByteArray();
                    return fileTypeDecode(gzLog);
                }
            }
        } catch (CosServiceException cs) {
           
            throw new BadRequestException("error.params.fileNameNotExist");
        } catch (CosClientException cc) {
          
            throw new BadRequestException("error.params.clientException");
        } catch (Exception e) {
            logger.error("获取ZIP压缩包内所有文件目录失败! 错误描述:" + e.getMessage());
            throw new BadRequestException("error.params.getZIPFileDirectoryFailure");
        } finally {
            try {
                if (bis != null) bis.close();
                if (tais != null) tais.close();
                if (gzis != null) gzis.close();
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                logger.error("获取压缩包中所有文件目录时关闭输入输出流失败!错误描述:" + e.getMessage());
            }
        }
        return null;
    }

五、预览文件内容乱码处理

 /**
     *解码获取文件的字符集编码格式
     */
    private byte[] fileTypeDecode(byte[] gzLog) {
        String strLog = null;
        String code = getCodeType(gzLog);
        logger.info("预览的文件字符集编码格式为:" + code);
        try {
            if ("utf8".equals(code)) {
                strLog = new String(gzLog, "UTF-8");
            } else if ("unicode".equals(code)) {
                strLog = new String(gzLog, "UNICODE");
            } else {
                strLog = new String(gzLog, "GBK");
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("解码获取文件的字符集编码格式失败!错误描述:" + e.getMessage());
        }
        if (StringUtils.isNotEmpty(strLog)) {
            return strLog.getBytes();
        }
        return null;
    }

参考API:

Apache Commons Compress 1.18 API

ZipFile

ZipInputStream

ZipEntry

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平凡之路无尽路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值