In Java: How to zip file from byte[] array?

前端 未结 7 2353
情话喂你
情话喂你 2020-11-28 03:36

My application is receiving email through SMTP server. There are one or more attachments in the email and email attachment return as byte[] (using sun javamail api).

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 03:59

    You can use Java's java.util.zip.ZipOutputStream to create a zip file in memory. For example:

    public static byte[] zipBytes(String filename, byte[] input) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        ZipEntry entry = new ZipEntry(filename);
        entry.setSize(input.length);
        zos.putNextEntry(entry);
        zos.write(input);
        zos.closeEntry();
        zos.close();
        return baos.toByteArray();
    }
    

提交回复
热议问题