How to send a zip file without creating it in a physical place?

I want to send an email with the zip file attachment. I can send PDF files without saving them to a physical location using ByteArrayOutputStream. But when I try to fix this file, send it inoperable. This gives an exception to illegal investment.

Below is the code I wrote to create the zip.

private MimeBodyPart zipAttachment( List<ByteArrayOutputStream> attachmentList, List<String> reportFileNames ) { MimeBodyPart messageBodyPart = null; try { // File file = File.createTempFile( "Reports.zip",".tmp" ); // FileOutputStream fout = new FileOutputStream(file); ByteArrayOutputStream bout = new ByteArrayOutputStream(attachmentList.size()); ZipOutputStream zos = new ZipOutputStream( bout ); ZipEntry entry; for( int i = 0; i < attachmentList.size(); i++ ) { ByteArrayOutputStream attachmentFile = attachmentList.get( i ); byte[] bytes = attachmentFile.toByteArray(); entry = new ZipEntry( reportFileNames.get( i ) ); entry.setSize( bytes.length ); zos.putNextEntry( entry ); zos.write( bytes ); } messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource( bout.toByteArray(), "application/zip" ); messageBodyPart.setDataHandler( new DataHandler( source ) ); messageBodyPart.setFileName( "Reports.zip" ); } catch( Exception e ) { // TODO: handle exception } return messageBodyPart; } 
+7
source share
2 answers

You forgot to call zos.closeEntry () after each item is written, at the end of the for loop. And, as already noted, you did not close your ZipOutputStream.

I don't think you need to call entry.setSize () as well.

Otherwise, this should work.

+2
source

I think you did not blush and close the ZipOutputStream . Try calling zos.flush(); zos.close() zos.flush(); zos.close() . I hope this helps.

If you are not trying to extract an array of bytes from your ByteArrayOutputStream , save it to a file and open it using the zip-enable tool. This is just for debugging, to make sure your zip is in order and not damaged.

0
source

All Articles