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?
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With