Ok, here is the final method - this is the same method that was run before I actually got from the stackoverflow theme in the @Qwe link posted earlier, but I added a path variable so that it can add files to folders inside zip
Ok, now, how to use it in my example above, I wanted to add a file to a folder that was inside another folder, I would do it using my setting in a question like this
private void addFilesToZip(File source, File[] files, String path){ try{ File tmpZip = File.createTempFile(source.getName(), null); tmpZip.delete(); if(!source.renameTo(tmpZip)){ throw new Exception("Could not make temp file (" + source.getName() + ")"); } byte[] buffer = new byte[4096]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source)); for(int i = 0; i < files.length; i++){ InputStream in = new FileInputStream(files[i]); out.putNextEntry(new ZipEntry(path + files[i].getName())); for(int read = in.read(buffer); read > -1; read = in.read(buffer)){ out.write(buffer, 0, read); } out.closeEntry(); in.close(); } for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()){ if(!zipEntryMatch(ze.getName(), files, path)){ out.putNextEntry(ze); for(int read = zin.read(buffer); read > -1; read = zin.read(buffer)){ out.write(buffer, 0, read); } out.closeEntry(); } } out.close(); tmpZip.delete(); }catch(Exception e){ e.printStackTrace(); } } private boolean zipEntryMatch(String zeName, File[] files, String path){ for(int i = 0; i < files.length; i++){ if((path + files[i].getName()).equals(zeName)){ return true; } } return false; }
Thanks for the link, which ultimately is able to slightly improve this method, so that it can add files that were not in the root directory, and now I am a happy tourist :) I hope this helps someone else too
EDIT I worked a bit on this method so that it can not only add to zip, but also update files in zip
Use a method like this
File[] files = {new File("/path/to/file/to/update/in")}; addFilesToZip(new File("/path/to/zip"), files, "folder/dir/");
You would not run the path (last variable) with / as it is not, as indicated in the zip entries
user577732 Feb 16 '12 at 3:21 2012-02-16 03:21
source share