2

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
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
yaniv
  • 152
  • 5
  • 15

1 Answers1

9

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.
AlexR
  • 114,158
  • 16
  • 130
  • 208
  • i m sorry , but i seem to be missing somthing here – yaniv May 09 '13 at 14:46
  • could you please add the code to convert the byte array back to a file. i seem to be having a problem with this too :-) , or even better to a FileInputStream so that i would be able to read it directly, thanks a lot – yaniv May 09 '13 at 15:18
  • @yaniv Make up your mind. You said your objective was 'to avoid the file system completely and not create the file'? – user207421 May 10 '13 at 01:32
  • my objective is simple, i have a file that is needed for my software – yaniv May 10 '13 at 22:12
  • my objective is simple, i have a file that is needed for my software, i wish to store this file as a zip in the db , and when the software needs it , it could take it from the db and read it. maybe i m wrong about saving it as a file and what i should do is save it to a string first and store the string it self in the db, but this way i will not be able to zip the information, thanks for your help if you could guide me to a solution – yaniv May 10 '13 at 22:20
  • 1
    @AlexR Thanks. I was googling for sometime to find out how to Zip a file and return as a byte array. Your suggestion helped. The only change I have is, I used zipBytes.toByteArray() instead of getBytes(). I'm in Java6. – SyAu Jan 21 '16 at 22:56