zip压缩文件转换为可传输byte[]流和不解压下读取指定zip包中文件
一、背景
最近做了一个项目,里面有这么一个需求:将zip文件存放到json字符串中。然后封装成报文发送给终端,终端在得到报文之后发送给终端,终端在获取到json字符串后读取内容并还原成zip文件包,而且要对zip文件中的某些特定文件内容进行入库保存。
要达到上面的要求,无非是要将zip文件转化成byte[],然后转化成Base64字符串存放到json字符串中和一个zip在未解压的情况下的指定文件读取。
光说不练假把式,上代码:
二、代码实现
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
- 将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);
- 将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);
- 读取未解压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) {