首页 > 技术文章 > 将多个文件打包到一个压缩包里面

cuiyueyang 2020-09-14 19:29 原文

public byte[] zip(List<String> fileNameList,List<String> filePathList) throws IOException {
    List<byte[]> listBytes = new ArrayList<>();
    for (String downPath :filePathList) {
        //从主机获得文件流
        InputStream is =new FileInputStream(downPath);
        byte[] down = IOUtils.toByteArray(is);
        listBytes.add(down);
        is.close();
    }

    ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream();
    ZipOutputStream out = new ZipOutputStream(fileOutputStream);
    ZipEntry entry = null;
    for (int i = 0; i < fileNameList.size(); i++) {
        byte[] tmpBytes = listBytes.get(i);
        String name = fileNameList.get(i);
        entry = new ZipEntry(name);
        // 存储项信息到压缩文件
        out.putNextEntry(entry);
        // 将文件的内容通过字节数组复制到压缩文件中
        out.write(tmpBytes, 0, tmpBytes.length);
        out.closeEntry();
    }
    out.close();
    out.flush();
    fileOutputStream.close();
    byte[] bytes = fileOutputStream.toByteArray();
    return bytes;
}
 

 

推荐阅读