2008-12-10 16 views
34

मेरा आवेदन एसएमटीपी सर्वर के माध्यम से ईमेल प्राप्त कर रहा है। ईमेल में एक या अधिक अनुलग्नक हैं और ईमेल संलग्नक बाइट [] के रूप में लौटते हैं (सूर्य जावमेल एपीआई का उपयोग करके)।जावा में: बाइट [] सरणी से फ़ाइल कैसे ज़िप करें?

मैं पहले डिस्क पर लिखने के बिना अनुलग्नक फ़ाइलों को फ्लाई पर ज़िप करने की कोशिश कर रहा हूं।

इस परिणाम को प्राप्त करने के लिए संभावित तरीका क्या है?

उत्तर

89

आप जावा के java.util.zip.ZipOutputStream का उपयोग स्मृति में एक ज़िप फ़ाइल बनाने में कर सकते हैं। उदाहरण के लिए:

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

आप महोदय, मेरा दिन बचाया जा सकता है! – Leo

+0

@ डेव - ZipOutputStream जाक्स-आरएस आउटपुट के रूप में भेजा जा सकता है – Varun

1

शायद 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. 
0

आप बाइट सरणी से एक ज़िप फ़ाइल बना सकते हैं और 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()); 
     } 
} 
संबंधित मुद्दे