Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ZipOutputStream to FileInputStream

i have a code that takes a file, zip it, and stores it in a database

looks like this

          // STEP 1 - Create a ZIP file
          byte[] buffer = new byte[1024];// 18024
          ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream("file.zip"));
          outZip.setLevel(Deflater.DEFAULT_COMPRESSION);
          FileInputStream in = new FileInputStream(c:\file.hex);
          outZip.putNextEntry(new ZipEntry("file.hex"));
          int len;
          while (( len = in.read(buffer)) > 0)
                outZip.write(buffer, 0, len);
          outZip.closeEntry();
          in.close();
          outZip.close();

          // STEP 2 - Insert zip file to DB
          file = new File("file.zip");
          FileInputStream fis = new FileInputStream( file );

the fis object i store in the DB

but i would like to avoid the filesystem completely , and not create the file.zip. i think i need to convert the ZipOutputStream into FileInputStream directly but i could not find a way to do it.

is there an easy way to accomplish this ?

  • i also have the same problem when i extract the file, in order to read it i must create 2 different temporary files - file.zip and file.hex
like image 514
yaniv Avatar asked Jan 27 '26 13:01

yaniv


1 Answers

You just do not have to create FileOutputStream at all. Use ByteArrayOutputStream instead:

ByteArrayOutputStream zipBytes = new ByteArrayOutputStream()
ZipOutputStream outZip = new ZipOutputStream(zipBytes);

// run your code that adds zip entries....

zipBytes.getBytes() // returns array of bytes that contain your zipped information.
like image 194
AlexR Avatar answered Jan 29 '26 02:01

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!