将多个文件打包到一个压缩包里面

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;
}
 

 

上一篇:高效 告别996,开启java高效编程之门 4-3传统方式关闭流资源


下一篇:IO字节流