Hello everyone.
I have formulated this question in order that they could give me a hand in the obstacle that has appeared in my path.
My problem
My problem is that I want to be able to compress the data or the contents of a folder in a zip, but my current compression code has not given me a positive or expected result. For the reason that it does not compress the desired
My code
public class Comp {
public static void zipDir(OutputStream zipFilename, String dir) throws Exception {
File dirObj = new File(dir);
ZipOutputStream out = new ZipOutputStream(zipFilename);
System.out.println("Creating : ");
addDir(dirObj, out);
out.close();
}
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
System.out.println(" Adding: " + files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
}
}
Explanation: my code is very simple, I only pass two parameters, one which is the ouputStream where it can be written and the other is where I pass the path of the folder where the content will be copied
And I call these methods from the activity where the compression process will be triggered as follows:
File file = new File(bb);
OutputStream os = driveContents1.getOutputStream();
Comp comp=new Comp();
try {
comp.zipDir(os, file.getAbsolutePath());
Toast.makeText(this, "Se COmprimimio", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you notice where I fail in my code or know other ways to achieve my goal. Please let me know. Thanks.
Your file is left empty because you recursively look for files (which aren't there) but never make entries for folders. I leave you an example that works (it is not production code, you should check the integrity of the produced zip).