Zipping InputStream returning InputStream (in memory, without file)

I am trying to compress an InputStream and return an InputStream:

public InputStream compress (InputStream in){ // Read "in" and write to ZipOutputStream // Convert ZipOutputStream into InputStream and return } 

I am compressing a single file (so I could use GZIP), but I will do more in the future (so I chose ZIP). In most places:

My problems:

  • How to convert ZipOutPutStream to InputStream if such methods do not exist?

  • When creating ZipOutPutStream (), there is no default constructor. Should I create a new ZipOutputStrem (new OutputStream ())?

+6
source share
2 answers
  • Solved it using ByteArrayOutputStream which has .toByteArray ()
  • Same thing by passing the above item
+2
source

Something like that:

 private InputStream compress(InputStream in, String entryName) throws IOException { final int BUFFER = 2048; byte buffer[] = new byte[BUFFER]; ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(out); zos.putNextEntry(new ZipEntry(entryName)); int length; while ((length = in.read(buffer)) >= 0) { zos.write(buffer, 0, length); } zos.closeEntry(); zos.close(); return new ByteArrayInputStream(out.toByteArray()); } 
+6
source

Source: https://habr.com/ru/post/950547/


All Articles