byte转换为string乱码_zip压缩文件转换为可传输byte[]流和不解压下读取指定zip包中文件...

6a2756d1a65ec169ebf942b1e3477162.png

一、背景

最近做了一个项目,里面有这么一个需求:将zip文件存放到json字符串中。然后封装成报文发送给终端,终端在得到报文之后发送给终端,终端在获取到json字符串后读取内容并还原成zip文件包,而且要对zip文件中的某些特定文件内容进行入库保存。

要达到上面的要求,无非是要将zip文件转化成byte[],然后转化成Base64字符串存放到json字符串中和一个zip在未解压的情况下的指定文件读取。

光说不练假把式,上代码:

二、代码实现

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
  1. 将zip文件转化为byte[]
public static byte[] readZipFileToByteArray(String filePath) throws Exception {
    File file = new File(filePath);
    if(!file.exists()){
        return new byte[0];
    }
    return FileUtils.readFileToByteArray(file);
}
  1. 将byte[]转化为zip文件
public static void convertByteArrayToZipFile(byte[] certFile,String filePath) throws IOException{
    File zipFile = new File(filePath);
    try (
        OutputStream out = new FileOutputStream(zipFile);
        ){
        out.write(certFile);
        out.flush();
    }catch (Exception e){
        throw new IOException(e);
    }
}
  1. 读取未解压zip包中指定文件内容
public static String getFileContent(String zipFilePath,String innerFileName) throws IOException {
        ZipFile zipFile = new ZipFile(zipFilePath);
        String collect = zipFile.stream().filter(entry -> {
            return ((ZipEntry) entry).getName().equals(innerFileName);
        }).map(e -> {

            try (
                    InputStream inputStream = zipFile.getInputStream((ZipEntry) e);
            ) {
                return IOUtils.toString(inputStream, "utf-8");
            } catch (IOException e1) {
                e1.printStackTrace();
                return "";
            }
        }).collect(Collectors.joining());
        return collect;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值