Unzipping Files Programmatically In Android
Solution 1:
This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.
The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:
ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class: -read a zip via its constructor ZipInputStream(FileInputStream) -read entries of files and directories via method getNextEntry() -read binary data of current entry via method read(byte) -close current entry via method closeEntry() -close the zip file via method close()
ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form: folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext
Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file.
Below class is used for unzip download zip and extract file and store your desire location.
publicclassUnzipUtil
{
private String zipFile;
private String location;
publicUnzipUtil(String zipFile, String location)
{
this.zipFile = zipFile;
this.location = location;
dirChecker("");
}
publicvoidunzip()
{
try
{
FileInputStreamfin=newFileInputStream(zipFile);
ZipInputStreamzin=newZipInputStream(fin);
ZipEntryze=null;
while ((ze = zin.getNextEntry()) != null)
{
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory())
{
dirChecker(ze.getName());
}
else
{
FileOutputStreamfout=newFileOutputStream(location + ze.getName());
byte[] buffer = newbyte[8192];
int len;
while ((len = zin.read(buffer)) != -1)
{
fout.write(buffer, 0, len);
}
fout.close();
zin.closeEntry();
}
}
zin.close();
}
catch(Exception e)
{
Log.e("Decompress", "unzip", e);
}
}
privatevoiddirChecker(String dir)
{
Filef=newFile(location + dir);
if(!f.isDirectory())
{
f.mkdirs();
}
}
}
MainActivity.Class:
publicclassMainActivityextendsActivity
{
privateProgressDialog mProgressDialog;
StringUrl="http://hasmukh/hb.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipFolder/";
StringStorezipFileLocation =Environment.getExternalStorageDirectory() + "/DownloadedZip";
StringDirectoryName=Environment.getExternalStorageDirectory() + "/unzipFolder/files/";
@OverrideprotectedvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadZipfile mew = newDownloadZipfile();
mew.execute(url);
}
//-This is method is used for Download Zip file from server and store in Desire location.classDownloadZipfileextendsAsyncTask<String, String, String>
{
String result ="";
@OverrideprotectedvoidonPreExecute()
{
super.onPreExecute();
mProgressDialog = newProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@OverrideprotectedStringdoInBackground(String... aurl)
{
int count;
try
{
URL url = newURL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = newBufferedInputStream(url.openStream());
OutputStream output = newFileOutputStream(StorezipFileLocation);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.close();
input.close();
result = "true";
} catch (Exception e) {
result = "false";
}
returnnull;
}
protectedvoidonProgressUpdate(String... progress)
{
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@OverrideprotectedvoidonPostExecute(String unused)
{
mProgressDialog.dismiss();
if(result.equalsIgnoreCase("true"))
{
try
{
unzip();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
}
}
}
//This is the method for unzip file which is store your location. And unzip folder will store as per your desire location.publicvoidunzip() throws IOException
{
mProgressDialog = newProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
newUnZipTask().execute(StorezipFileLocation, DirectoryName);
}
privateclassUnZipTaskextendsAsyncTask<String, Void, Boolean>
{
@SuppressWarnings("rawtypes")
@OverrideprotectedBooleandoInBackground(String... params)
{
String filePath = params[0];
String destinationPath = params[1];
File archive = newFile(filePath);
try
{
ZipFile zipfile = newZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();)
{
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
UnzipUtil d = newUnzipUtil(StorezipFileLocation, DirectoryName);
d.unzip();
}
catch (Exception e)
{
returnfalse;
}
returntrue;
}
@OverrideprotectedvoidonPostExecute(Boolean result)
{
mProgressDialog.dismiss();
}
privatevoidunzipEntry(ZipFile zipfile, ZipEntry entry,String outputDir) throws IOException
{
if (entry.isDirectory())
{
createDir(newFile(outputDir, entry.getName()));
return;
}
File outputFile = newFile(outputDir, entry.getName());
if (!outputFile.getParentFile().exists())
{
createDir(outputFile.getParentFile());
}
// Log.v("", "Extracting: " + entry);BufferedInputStream inputStream = newBufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = newBufferedOutputStream(newFileOutputStream(outputFile));
try
{
}
finally
{
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
privatevoidcreateDir(File dir)
{
if (dir.exists())
{
return;
}
if (!dir.mkdirs())
{
thrownewRuntimeException("Can not create dir " + dir);
}
}}
}
Note: Do not forgot to add below permission in android Manifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permissionandroid:name="android.permission.INTERNET" />
Solution 2:
Unzip Function
publicvoidunzip(String _zipFile, String _targetLocation) {
//create target location folder if not exist
dirChecker(_targetLocatioan);
try {
FileInputStreamfin=newFileInputStream(_zipFile);
ZipInputStreamzin=newZipInputStream(fin);
ZipEntryze=null;
while ((ze = zin.getNextEntry()) != null) {
//create dir if required while unzipping if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStreamfout=newFileOutputStream(_targetLocation + ze.getName());
for (intc= zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
Initialization
ZipManagerzipManager=newZipManager();
zipManager.unzip(inputPath + inputFile, outputPath);
Solution 3:
For android, there is a third party library to be used for free. this library will download your file itself and extract it automatically wherever you want. you can check this library here. ExtractionLib for Android
Post a Comment for "Unzipping Files Programmatically In Android"