Last active
August 30, 2022 10:45
-
-
Save molidev8/5a9cb97c374f6d58817831ba27a12f42 to your computer and use it in GitHub Desktop.
Zip/Unzip of a file in Android
This file contains hidden or 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
/** | |
* Compress all the files for the backup into a .zip file | |
* @param output A [FileOutputStream] where the zip file is going to be saved | |
* @param input The files that are going to be compressed into the .zip file | |
*/ | |
private fun zipFiles(output: FileOutputStream, vararg input: File?) { | |
val zipOutput = ZipOutputStream(BufferedOutputStream(output)) | |
val addZipEntry = { file: File -> | |
val entry = ZipEntry(file.name) | |
val zipInput = BufferedInputStream(FileInputStream(file)) | |
zipOutput.putNextEntry(entry) | |
zipInput.run { | |
copyTo(zipOutput) | |
close() | |
} | |
zipOutput.closeEntry() | |
} | |
try { | |
input.forEach { file -> | |
file?.let { | |
if (!file.isDirectory) addZipEntry(file) | |
else file.listFiles()?.forEach { file -> | |
if (file.extension == "jpg") addZipEntry(file) | |
} | |
} | |
} | |
zipOutput.close() | |
} catch (e: IllegalArgumentException) { | |
throw Exception() | |
} catch (e: ZipException) { | |
throw Exception() | |
} catch (e: IOException) { | |
throw Exception() | |
} | |
} | |
/** | |
* Decompresses the .zip file with the files for the restoration process into the Documents folder | |
*/ | |
private fun unzipBackupFiles() { | |
val input = | |
ZipFile(backupDir?.path + "/recipe-vault-backup.zip") | |
val entries: Enumeration<out ZipEntry?> = input.entries() | |
while (entries.hasMoreElements()) { | |
val entry = entries.nextElement() | |
val output = entry?.run { | |
if (name == "recipes_db") | |
BufferedOutputStream(FileOutputStream(File(backupDir, name))) | |
else | |
BufferedOutputStream(FileOutputStream(File(photosDir, name))) | |
} | |
val data = input.getInputStream(entry) | |
val bytes = data.readBytes() | |
output?.write(bytes) | |
data.close() | |
output?.close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment