我想压缩一个结构如下的文件夹:
临时/文件夹1/文件1
临时/文件夹2/文件2
临时/文件3
并准确维护目录结构。目前,当我压缩它时,我得到一个不维护目录结构的 zip。看起来像这个 file1 file2 file3
我该怎么做才能像所有普通的压缩应用程序一样将文件添加到各自的文件夹中?
这是我到目前为止的代码:
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();
}
}
}