io - How to zip files and folders in Java? -


please have @ below code.

public void startcompress(string path,string filename,string outputlocation,int compresstype,int filsize) throws exception     {                 system.out.println("input location: "+path);         system.out.println("output location: "+outputlocation);                 system.out.println(compresstype);             byte[] bs=new byte[filsize];             system.out.println(filsize);              fileoutputstream fos=new fileoutputstream(outputlocation+"/test.zip");              system.out.println(fos.tostring());             zipoutputstream zos=new zipoutputstream(fos);              zipentry ze = new zipentry(filename);              zos.putnextentry(ze);              fileinputstream inputstream=new fileinputstream(path);              int len;             while((len=inputstream.read(bs))>0){                 zos.write(bs, 0, len);                             }             inputstream.close();             zos.closeentry();             zos.close();      } 

in above code, compress file using java.util.zip package. have issue. is, if select multiple files 1 file being compressed. if select folder, compression won't work.

how can fix compress either file, files, folder, folders, or nested folders? java zip package support .zip, .tar, .targz , tarz. solution should not limited .zip extension well.

the zip libraries java cannot used compress folders in simpler way - compress folder.

you need test if input folder or file yourself. if file - add zip. if folder - iterate folder , add each file zip. subfolders same. add more 1 file zip need create zipentry each file.

you can try code works me:

public static void zip(file directory, file zipfile) throws ioexception {     uri base = directory.touri();     deque<file> queue = new linkedlist<file>();     queue.push(directory);     outputstream out = new fileoutputstream(zipfile);     closeable res = out;     try {         zipoutputstream zout = new zipoutputstream(out);         res = zout;         while (!queue.isempty()) {             directory = queue.pop();             (file kid : directory.listfiles()) {                 string name = base.relativize(kid.touri()).getpath();                 if (kid.isdirectory()) {                     queue.push(kid);                     name = name.endswith("/") ? name : name + "/";                     zout.putnextentry(new zipentry(name));                 } else {                     zout.putnextentry(new zipentry(name));                     copy(kid, zout);                     zout.closeentry();                 }             }         }     } {         res.close();     } } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -