2008-12-10 38 views
34

Ứng dụng của tôi đang nhận email thông qua máy chủ SMTP. Có một hoặc nhiều tệp đính kèm trong email và tệp đính kèm email trả về dưới dạng byte [] (sử dụng api javamail mặt trời).Trong Java: Cách nén tệp từ mảng byte []?

Tôi đang cố nén các tệp đính kèm mà không cần ghi chúng vào đĩa trước.

Cách/có thể là gì để đạt được kết quả này?

Trả lời

89

Bạn có thể sử dụng java.util.zip.ZipOutputStream Java để tạo ra một tập tin zip trong bộ nhớ. Ví dụ:

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

Bạn ạ, lưu ngày của tôi! – Leo

+0

@Dave - có thể ZipOutputStream được gửi dưới dạng đầu ra jax-rs không – Varun

1

lẽ gói java.util.zip có thể giúp bạn

Vì bạn đang hỏi về làm thế nào để chuyển đổi từ mảng byte Tôi nghĩ (không kiểm tra), bạn có thể sử dụng phương pháp 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. 

rằng bạn sẽ ăn đến

ZipInputStream This class implements an input stream filter for reading files in the ZIP file format. 
0

Bạn có thể tạo một file zip từ mảng byte và trở về 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()); 
     } 
} 
Các vấn đề liên quan