Skip to main content

How to compress a file in Kotlin

How to compress a file in Kotlin.

Here's a detailed step-by-step tutorial on how to compress a file in Kotlin:

Step 1: Import Required Libraries

To compress a file in Kotlin, we need to use the java.util.zip package. Add the following import statement at the beginning of your Kotlin file:

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

Step 2: Define the Function

Next, we need to define a function that takes the path of the file to be compressed and the path for the compressed file as input. Here's an example function named compressFile():

fun compressFile(sourceFilePath: String, destinationFilePath: String) {
val bufferSize = 1024
val buffer = ByteArray(bufferSize)

try {
// Create a FileInputStream for the source file
val sourceFileStream = FileInputStream(sourceFilePath)
val bufferedInputStream = BufferedInputStream(sourceFileStream, bufferSize)

// Create a FileOutputStream for the destination file
val destinationFileStream = FileOutputStream(destinationFilePath)
val zipOutputStream = ZipOutputStream(destinationFileStream)

// Create a new ZipEntry with the name of the source file
val zipEntry = ZipEntry(sourceFilePath)

// Put the ZipEntry in the ZipOutputStream
zipOutputStream.putNextEntry(zipEntry)

// Read the source file and write it to the ZipOutputStream
var length: Int
while (bufferedInputStream.read(buffer, 0, bufferSize).also { length = it } >= 0) {
zipOutputStream.write(buffer, 0, length)
}

// Close the streams
bufferedInputStream.close()
zipOutputStream.closeEntry()
zipOutputStream.close()

// Print success message
println("File compressed successfully.")
} catch (e: Exception) {
// Print error message
println("Error compressing the file: ${e.message}")
}
}

Step 3: Call the Function

To compress a file, you can call the compressFile() function and provide the source file path and the destination file path as arguments. Here's an example of how to call the function:

val sourceFilePath = "path/to/source/file.txt"
val destinationFilePath = "path/to/destination/file.zip"

compressFile(sourceFilePath, destinationFilePath)

Make sure to replace "path/to/source/file.txt" with the actual path of the file you want to compress, and "path/to/destination/file.zip" with the desired path and filename for the compressed file.

Step 4: Run the Code

Save your Kotlin file and run it. If everything is set up correctly, the source file will be compressed and a success message will be printed. If any error occurs during the compression process, an error message will be displayed instead.

That's it! You have successfully compressed a file in Kotlin using the java.util.zip package.