Last active
October 6, 2023 06:38
-
-
Save prakashpro3/955d3cf82ca954037e92b497f0fb5d85 to your computer and use it in GitHub Desktop.
Compress files to zip and unzip in android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedInputStream | |
import java.io.BufferedOutputStream | |
import java.io.File | |
import java.io.FileInputStream | |
import java.io.FileOutputStream | |
import java.io.IOException | |
import java.util.zip.ZipEntry | |
import java.util.zip.ZipInputStream | |
import java.util.zip.ZipOutputStream | |
object ZipManagerAndroid { | |
private const val BUFFER_SIZE = 6 * 1024 | |
@Throws(IOException::class) | |
fun zip(files: Array<String>, zipFile: String?) { | |
var origin: BufferedInputStream | |
ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use { out -> | |
val data = ByteArray(BUFFER_SIZE) | |
for (file in files) { | |
val fi = FileInputStream(file) | |
origin = BufferedInputStream(fi, BUFFER_SIZE) | |
try { | |
val entry = ZipEntry(file.substring(file.lastIndexOf("/") + 1)) | |
out.putNextEntry(entry) | |
var count: Int | |
while (origin.read(data, 0, BUFFER_SIZE).also { count = it } != -1) { | |
out.write(data, 0, count) | |
} | |
} finally { | |
origin.close() | |
} | |
} | |
} | |
} | |
@Throws(IOException::class) | |
fun unzip(zipFile: String?, location: String) { | |
try { | |
val f = File(location) | |
if (!f.isDirectory) { | |
f.mkdirs() | |
} | |
val zin = ZipInputStream(FileInputStream(zipFile)) | |
try { | |
var ze: ZipEntry? = null | |
while (zin.nextEntry.also { ze = it } != null) { | |
val path = location + File.separator + ze!!.name | |
if (ze!!.isDirectory) { | |
val unzipFile = File(path) | |
if (!unzipFile.isDirectory) { | |
unzipFile.mkdirs() | |
} | |
} else { | |
val fout = FileOutputStream(path, false) | |
try { | |
var c = zin.read() | |
while (c != -1) { | |
fout.write(c) | |
c = zin.read() | |
} | |
zin.closeEntry() | |
} finally { | |
fout.close() | |
} | |
} | |
} | |
} finally { | |
zin.close() | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
SystemUtils.setLog("unzip", "Unzip exception - $e") | |
} | |
} | |
@Throws(IOException::class) | |
private fun howToCallZip() { | |
val sourceFilePath = "sourceFilePathToBeAddToZip" | |
val destinationDirPath = "sestinationFilePathToBeStoreAfterZip" | |
val s = arrayOf(sourceFilePath) | |
zip(s, destinationDirPath) | |
} | |
private fun howToCallUnzip() { | |
val zipFilePath = "sourceFilePathToBeUnzip" | |
val destinationPath = "destinationFilePathToBeStoreAfterUnzip" | |
unzip(zipFilePath, destinationPath); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment