How to Unzip Files Programmatically in Android

How to programmatically see whats is inside a zip in android (without unzip)

Use ZipFile: it uses random access to jump between file positions in the zip archive:

try (ZipFile file = new ZipFile("file.zip")) {
final Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
System.out.println(entry.getName());
}
}

How to zip and unzip the files?

Take a look at java.util.zip.* classes for zip functionality. I've done some basic zip/unzip code, which I've pasted below. Hope it helps.

public static void zip(String[] files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];

for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
}
finally {
origin.close();
}
}
}
finally {
out.close();
}
}

public static void unzip(String zipFile, String location) throws IOException {
try {
File f = new File(location);
if(!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();

if (ze.isDirectory()) {
File unzipFile = new File(path);
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
}
else {
FileOutputStream fout = new FileOutputStream(path, false);
try {
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
}
finally {
fout.close();
}
}
}
}
finally {
zin.close();
}
}
catch (Exception e) {
Log.e(TAG, "Unzip exception", e);
}
}

Android Unzip zip file

You can use open source "zt-zip" to solve your problem:zt-zip

Unzip files programmatically in .net

We have used SharpZipLib successfully on many projects. I know it's a third party tool, but source code is included and could provide some insight if you chose to reinvent the wheel here.



Related Topics



Leave a reply



Submit