Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Zip File in Memory

I'm trying to zip a file (for example foo.csv) and upload it to a server. I have a working version which creates a local copy and then deletes the local copy. How would I zip a file so I could send it without writing to the hard drive and do it purely in memory?

like image 509
Sleep Deprived Bulbasaur Avatar asked May 12 '14 15:05

Sleep Deprived Bulbasaur


People also ask

How do I create a new zip file?

Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location. To rename it, press and hold (or right-click) the folder, select Rename, and then type the new name.

Can Windows 10 create Zip files?

Zipping is one of the oldest and most commonly used methods for compressing files. It's used to save space and share big files quickly. In the past, you needed third-party programs like WinZip to unzip files in Windows. But Windows 10 lets you zip and unzip any file you want just by right-clicking.

How do I automatically zip a folder?

Right-click on the folder/folders from which the files need to be copied and choose Copywhiz–>Copy from the menu as shown below: Go to the destination folder where you wish to create the . zip file and select Copywhiz–> Paste Advanced. Under the paste options select 'Paste as compressed .

How do I create a zip file from archive?

Browse one level above the folder you want to archive, right-click on it and choose 7-Zip followed by Add to archive... and OK. A new archive file has now been created, named the same as your original folder, with a . zip extension. It contains all the files in the folder.


1 Answers

Use ByteArrayOutputStream with ZipOutputStream to accomplish the task.

you can use ZipEntry to specify the files to be included into the zip file.

Here is an example of using the above classes,

String s = "hello world";  ByteArrayOutputStream baos = new ByteArrayOutputStream(); try(ZipOutputStream zos = new ZipOutputStream(baos)) {    /* File is not on the disk, test.txt indicates      only the file name to be put into the zip */   ZipEntry entry = new ZipEntry("test.txt");     zos.putNextEntry(entry);   zos.write(s.getBytes());   zos.closeEntry();    /* use more Entries to add more files      and use closeEntry() to close each file entry */    } catch(IOException ioe) {     ioe.printStackTrace();   } 

now baos contains your zip file as a stream

like image 69
Thirumalai Parthasarathi Avatar answered Sep 25 '22 11:09

Thirumalai Parthasarathi