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

前端 未结 7 2316
情话喂你
情话喂你 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:55

       byte[] createReport() {
        try {
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         ZipArchiveOutputStream zipOutputStream = new 
         ZipArchiveOutputStream(byteArrayOutputStream);
         
         zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
         zipOutputStream.setEncoding(ENCODING);
    
         String text= "text";
         byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
    
         ArchiveEntry zipEntryReportObject = newStoredEntry("file.txt", textBytes);
         zipOutputStream.putArchiveEntry(zipEntryReportObject);
         zipOutputStream.write(textBytes);
    
         zipOutputStream.closeArchiveEntry();
         zipOutputStream.close();
        
         return byteArrayOutputStream.toByteArray();
         } catch (IOException e) {
           return null;
        }
    

    and

    ArchiveEntry newStoredEntry(String name, byte[] data) {
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(name);
        zipEntry.setSize(data.length);
        zipEntry.setCompressedSize(zipEntry.getSize());
        CRC32 crc32 = new CRC32();
        crc32.update(data);
        zipEntry.setCrc(crc32.getValue());
        return zipEntry;
      }
    

提交回复
热议问题