在Java中:如何从byte []数组中压缩文件? [英] In Java: How to zip file from byte[] array?

查看:131
本文介绍了在Java中:如何从byte []数组中压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过SMTP服务器接收电子邮件。电子邮件和电子邮件附件中有一个或多个附件返回byte [](使用sun javamail api)。

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).

我试图在运行时压缩附件文件没有先将它们写入磁盘。

I am trying to zip the attachment files on the fly without writing them to disk first.

实现这一结果的可行方法是什么?

What is/are possible way to achieve this outcome?

推荐答案

您可以使用Java的java.util.zip.ZipOutputStream在内存中创建一个zip文件。例如:

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

这篇关于在Java中:如何从byte []数组中压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆