private ProgressDialog mProgressDialog;
private String unzipLocation = Environment.getExternalStorageDirectory() + "/";
private String zipFile = Environment.getExternalStorageDirectory() + "/xxx.zip";
unzip();
public void unzip() throws IOException {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please Wait...Extracting zip file ... ");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
new UnZipTask().execute(zipFile, unzipLocation);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean> {
@SuppressWarnings("rawtypes")
@Override
protected Boolean doInBackground(String... params) {
String filePath = params[0];
String destinationPath = params[1];
File archive = new File(filePath);
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
UnZipUtil d = new UnZipUtil();
d.unZip(zipFile, unzipLocation);
} catch (Exception e) {
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
mProgressDialog.dismiss();
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry, String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
// Log.v("", "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
} finally {
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
if (dir.exists()) {
return;
}
if (!dir.mkdirs()) {
throw new RuntimeException("Can not create dir " + dir);
}
}
}
public class UnZipUtil {
public boolean unZip(String zipFile, String ToPath) {
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(zipFile);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
// zapis do souboru
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(ToPath + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(ToPath + filename);
// cteni zipu a zapis
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
} catch(IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
}
댓글 없음:
댓글 쓰기