Welcome to this comprehensive guide on using Kotlin's built-in support for archiving and extracting files using the java.util.zip package! In this tutorial, we'll cover everything you need to know about zip and unzip operations in Kotlin, starting from the basics and gradually moving towards more advanced examples. š
Zip is a file format that enables the compression of multiple files into a single archive, making it easier to store and transfer them. Unzip, as the name suggests, is the process of extracting files from a ZIP archive.
Before we dive into the code, let's create a new Kotlin project in Android Studio:
Now let's create a simple Kotlin program to generate a ZIP archive:
import java.io.File
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
fun main(args: Array<String>) {
val baseDir = File("src/main/java/com/example/myapp") // Replace with your project directory
val zipFile = File("myArchive.zip")
ZipOutputStream(zipFile.outputStream()).use { zipOut ->
baseDir.walk().filter { it.isFile || it.isDirectory }
.forEach { path ->
val zipEntry = ZipEntry(path.toString().replace(baseDir.toString(), ""))
zipOut.putNextEntry(zipEntry)
if (path.isFile) {
val fileContent = File(path).readBytes()
zipOut.write(fileContent)
}
zipOut.closeEntry()
}
}
println("Zip file created: $zipFile")
}š Note: Replace com/example/myapp with your project's package name. This code will create a ZIP file named myArchive.zip in your project's root directory, containing all the files and directories under src/main/java.
To extract a ZIP archive, you can use the ZipFile class in Kotlin:
import java.io.File
import java.util.zip.ZipFile
fun main(args: Array<String>) {
val zipFile = File("myArchive.zip")
if (zipFile.exists()) {
ZipFile(zipFile).use { zip ->
for (entry in zip.entries()) {
if (entry.isDirectory) continue
val destFile = File(zipFile.parentFile, entry.name)
destFile.parentFile.mkdirs()
zip.getInputStream(entry).use { inputStream ->
inputStream.use { file ->
file.copyTo(destFile)
}
}
}
}
println("Zip file extracted successfully.")
} else {
println("Zip file not found.")
}
}š Note: Replace myArchive.zip with the name of your ZIP file. This code will extract all the files and directories from the myArchive.zip file in the same directory as the ZIP file.
What is the purpose of using Zip and Unzip Operations in Kotlin?
By now, you have a good understanding of working with zip and unzip operations in Kotlin. Happy coding! š