I want zip up a folder structured like so:
temp/folder1/file1
temp/folder2/file2
temp/file3
and maintain the directory structure exactly.
Currently, when I zip it, I get a zip that doesnt maintain the directory structure. It looks like this
file1
file2
file3
what do I do to add the files in their respective folders like all the normal zipping applications do?
This is the code I have so far:
package com.damastah.deflash;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Compress {
private static final int BUFFER = 2048;
private ArrayList<File> _files;
private String _zipFile;
public Compress(ArrayList<File> files, String zipFile) {
_files = files;
_zipFile = zipFile;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
Log.e("Compress - zip", "test");
for (int i = 0; i < _files.size(); i++) {
Log.v("Compress", "Adding: " + _files.get(i).getAbsolutePath());
FileInputStream fi = new FileInputStream(_files.get(i)
.getAbsolutePath());
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry;
if (_files.get(i).getAbsolutePath().contains("."))
entry = new ZipEntry(_files
.get(i)
.getAbsolutePath()
.substring(
_files.get(i).getAbsolutePath()
.lastIndexOf("/") + 1));
else
entry = new ZipEntry(_files.get(i).getAbsolutePath());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am not android developer so consider this code as a TIP only
Edit
I am not sure what you want to do here
From what i see it removes path to file leaving just file name (something like
_files.get(i).getName()). If that is true then that is why you don’t have folder structure in your zip file. You are saying that zip entry should be just that file name, without any folders.So if you want zip file to contain some part of path from
/my/full/path/to/folder/temp/folder1/file1liketemp/folder1/file1just remove unnecessary part of that path when you create ZipEntry for example