Skip to main content

How to read and write compressed files (ZIP, GZIP, etc.) in Kotlin

How to read and write compressed files (ZIP, GZIP, etc.) in Kotlin.

Here's a step-by-step tutorial on how to read and write compressed files (ZIP, GZIP, etc.) in Kotlin:

Reading Compressed Files

Reading ZIP Files

To read a ZIP file in Kotlin, you can use the java.util.zip.ZipFile class. Here's an example:

import java.util.zip.ZipFile

fun main() {
val zipFile = ZipFile("path/to/file.zip")

// Get the entries in the ZIP file
val entries = zipFile.entries()

// Iterate over the entries
while (entries.hasMoreElements()) {
val entry = entries.nextElement()

// Read the contents of the entry
val inputStream = zipFile.getInputStream(entry)
// Process the inputStream as needed
}

// Close the ZIP file
zipFile.close()
}

Reading GZIP Files

To read a GZIP file in Kotlin, you can use the java.util.zip.GZIPInputStream class. Here's an example:

import java.io.FileInputStream
import java.util.zip.GZIPInputStream

fun main() {
val inputStream = GZIPInputStream(FileInputStream("path/to/file.gz"))

// Read the contents of the GZIP file
// Process the inputStream as needed

// Close the GZIP file
inputStream.close()
}

Writing Compressed Files

Writing ZIP Files

To write a ZIP file in Kotlin, you can use the java.util.zip.ZipOutputStream class. Here's an example:

import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

fun main() {
val zipFile = ZipOutputStream(FileOutputStream("path/to/file.zip"))

// Create a new entry in the ZIP file
val entry = ZipEntry("file.txt")
zipFile.putNextEntry(entry)

// Write the contents to the entry
// Process the outputStream as needed

// Close the entry
zipFile.closeEntry()

// Close the ZIP file
zipFile.close()
}

Writing GZIP Files

To write a GZIP file in Kotlin, you can use the java.util.zip.GZIPOutputStream class. Here's an example:

import java.io.FileOutputStream
import java.util.zip.GZIPOutputStream

fun main() {
val outputStream = GZIPOutputStream(FileOutputStream("path/to/file.gz"))

// Write the contents to the GZIP file
// Process the outputStream as needed

// Close the GZIP file
outputStream.close()
}

That's it! You now know how to read and write compressed files (ZIP, GZIP, etc.) in Kotlin.