ZipActivity
public class ZipActivity extends Activity {
private static String TAG = "ZipActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.zip("/mnt/sdcard/20111108.zip");
}
private void zip(String zipFilePath) {
Log.d(TAG, "Zip to: " + zipFilePath);
// 取得SD卡目錄,並以前一個範例產生的目錄做來壓縮目標
File sourceDir = new File(Environment.getExternalStorageDirectory(),
"idv.neil.unzip");
if (!sourceDir.exists()) {
Log.e(TAG, "Can't find this path: " + sourceDir.getAbsolutePath());
return;
}
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFilePath)));
zos = this.doZip(zos, sourceDir, null);
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
}
finally {
if (zos != null) {
try {
zos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
private ZipOutputStream doZip(ZipOutputStream zos, File sourceDir,
String folder) throws FileNotFoundException, IOException {
File[] sourceFiles = sourceDir.listFiles();
BufferedInputStream bis;
ZipEntry entry;
String path;
for (int i = 0; i < sourceFiles.length; i++) {
path = (folder == null ? "" : folder + "/")
+ sourceFiles[i].getName();
if (sourceFiles[i].isDirectory()) {
// 如果是目錄,就往下一層
Log.d(TAG,
"Open a directory: " + sourceFiles[i].getAbsolutePath());
this.doZip(zos, new File(sourceDir, sourceFiles[i].getName()),
path);
}
else {
Log.d(TAG, "Zip a file: " + sourceFiles[i].getAbsolutePath());
bis = new BufferedInputStream(new FileInputStream(
sourceFiles[i]));
entry = new ZipEntry(path);
zos.putNextEntry(entry);
int data = 0;
while ((data = bis.read()) != -1) {
zos.write(data);
}
bis.close();
}
}
zos.flush();
return zos;
}
}相關文章

沒有留言:
張貼留言