Comprimere e decomprimere file 7zip in Kotlin

Mattepuffo's logo
Comprimere e decomprimere file 7zip in Kotlin

Comprimere e decomprimere file 7zip in Kotlin

Tempo fa ho fatto in articolo su come comprimere/decomprimere file 7zip in Java.

Oggi vediamo come farlo in Kotlin.

Prima aggiungiamo una dipendenza; io uso gradle:

dependencies {
    ..............

    implementation("org.apache.commons:commons-compress:1.21")
}

Qui sotto il codice Kotlin:

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile
import java.io.File
import java.io.IOException
import java.nio.file.Files

fun main(args: Array<String>) {
    crea7zip(File("CARTELLA"));
    decomprimi7zip(File("test.7z"));
}

fun crea7zip(cartellaDaZippare: File) {
    val sevenZOutputFile = SevenZOutputFile(File("test.7z"))
    File(cartellaDaZippare.absolutePath).walk().forEach {
        val file = it
        if (file.exists()) {
            println("PROCESSO " + file)
            val sevenZArchiveEntry = sevenZOutputFile.createArchiveEntry(file, file.getName())
            sevenZOutputFile.putArchiveEntry(sevenZArchiveEntry)
            sevenZOutputFile.write(Files.readAllBytes(file.toPath()))
            sevenZOutputFile.closeArchiveEntry()
        }
    }

    sevenZOutputFile.finish()
}

fun decomprimi7zip(file7zip: File) {
    try {
        val sevenZFile = SevenZFile(file7zip)
        var entry: SevenZArchiveEntry
        while ((sevenZFile.nextEntry.also { entry = it }) != null) {
            val file = File(entry.getName())
            println("Un seven zipping - " + file)
            val dir = file.toPath().toString().substring(0, file.toPath().toString().lastIndexOf("\"))
            Files.createDirectories(File(dir).toPath())
            val content = ByteArray(entry.size.toInt())
            sevenZFile.read(content);
            Files.write(file.toPath(), content);
        }
    } catch (e: IOException) {
        println(e.message)
    }
}

Enjoy!


Condividi

Commentami!