web-dev-qa-db-ja.com

Javaの場合:byte []配列からファイルを圧縮する方法は?

私のアプリケーションは、SMTPサーバーを介して電子メールを受信して​​います。電子メールには1つ以上の添付ファイルがあり、電子メールの添付ファイルはbyte []として返されます(Sun javamail apiを使用)。

最初に添付ファイルをディスクに書き込むことなく、オンザフライで圧縮しようとしています。

この結果を達成するための可能な方法は何ですか?

41
netic

JavaのJava.util.Zip.ZipOutputStreamを使用して、メモリ内にZipファイルを作成できます。例えば:

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();
}
106
Dave L.

私は同じ問題を抱えていますが、Zipに多くのファイルが必要でした。

protected byte[] listBytesToZip(Map<String, byte[]> mapReporte, String extension) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    for (Entry<String, byte[]> reporte : mapReporte.entrySet()) {
        ZipEntry entry = new ZipEntry(reporte.getKey() + extension);
        entry.setSize(reporte.getValue().length);
        zos.putNextEntry(entry);
        zos.write(reporte.getValue());
    }
    zos.closeEntry();
    zos.close();
    return baos.toByteArray();
}
2
Jesús Sánchez

Java.util.Zip パッケージが役立つかもしれません

あなたはバイト配列から変換する方法について尋ねているので、(テストされていない)ByteArrayInputStreamメソッドを使用できると思います

int     read(byte[] b, int off, int len)
          Reads up to len bytes of data into an array of bytes from this input stream.

あなたがに送ります

ZipInputStream  This class implements an input stream filter for reading files in the Zip file format.
1
Eric

バイト配列からZipファイルを作成し、ui streamedContentに戻ることができます。

public StreamedContent getXMLFile() {
        try {
            byte[] blobFromDB= null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos);
            String fileName= "fileName";
            ZipEntry entry = new ZipEntry(fileName+".xml");
            entry.setSize(byteArray.length);
            zos.putNextEntry(entry);
            zos.write(byteArray);
            zos.closeEntry();
            zos.close();
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            StreamedContent zipedFile= new DefaultStreamedContent(is,   "application/Zip", fileName+".Zip", Charsets.UTF_8.name());
            return fileDownload;
        } catch (IOException e) {
            LOG.error("IOException e:{} ",e.getMessage());
        } catch (Exception ex) {
            LOG.error("Exception ex:{} ",ex.getMessage());
        }
}
0
Maciej

そのためにはZipOutputStreamを使用する必要があります。

http://Java.Sun.com/javase/6/docs/api/Java/util/Zip/ZipOutputStream.html

0
OscarRyz