Reputation: 20132
I have a nice java code that unzips a .zip file. But problem with this code is
So This code wont work if zip file content is not known before. so i think this is useless code. Anyone have better logic? or Bellow code need to be edited?
package com.mireader;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress {
private String _zipFile;
private String _location;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
byte[] buffer = new byte[1024];
int length;
int i=0;
while ((ze = zin.getNextEntry()) != null) {
Log.v("t", ze.toString());
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
Log.i("my","Comes to if");
_dirChecker(ze.getName());
}
else {
Log.i("my","Comes to else");
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
Log.i("My tag","Success");
}catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
Log.i("mytag", "Creating new folder");
f.mkdirs();
System.out.print("stp:"+f.getName());
}
}
}
Upvotes: 0
Views: 2535
Reputation: 1216
You can avoid the following piece of code
if(ze.isDirectory()) {
Log.i("my","Comes to if");
_dirChecker(ze.getName());
}
and add code similar to the one below in the file creator else part. It worked for me by creating the entire parent folders.
File file = createFile((baseDirectory +"/" + zipFile.getName()));
file.getParentFile().mkdirs();
Upvotes: 2
Reputation: 1279
It doesn't look that wrong, what exactly is your problem? You create the directories as they appear in the zip file; I usually do it inline, but it's the same. Your code would fail if your zip file not has the directory stubs inside (which could happen with zip creators in the wild), so my unzip code doublechecks the existance of the directory before extracting each file:
if (zEntry.isDirectory()) new File(destDir+zEntry.getName()).mkdirs();
else
{
String dstEntryDir=new File(destDir+zEntry.getName()).getParent()+File.separator;
if (!fileExists(dstEntryDir)) new File(dstEntryDir).mkdirs();
copyStreamToFile(zFile.getInputStream(zEntry),destDir+zEntry.getName());
}
Upvotes: 0