triad
triad

Reputation: 21537

Unzip a file in kotlin script [.kts]

I was toying with the idea of rewriting some existing bash scripts in kotlin script.

One of the scripts has a section that unzips all the files in a directory. In bash:

unzip *.zip

Is there a nice way to unzip a file(s) in kotlin script?

Upvotes: 8

Views: 16685

Answers (3)

Shahriar Zaman
Shahriar Zaman

Reputation: 938

The accepted answer will fail if the very first entry of the zip is a directory. This is a slightly modified solution to handle the issue.

/**
 * Extract a zip file into any directory
 *
 * @param zipFile src zip file
 * @param extractTo directory to extract into.
 * There will be new folder with the zip's name inside [extractTo] directory.
 * @param extractHere no extra folder will be created and will be extracted
 * directly inside [extractTo] folder.
 *
 * @return the extracted directory i.e, [extractTo] folder if [extractHere] is `true`
 * and [extractTo]\zipFile\ folder otherwise.
 */
private fun extractZipFile(
    zipFile: File,
    extractTo: File,
    extractHere: Boolean = false,
): File? {
    return try {
        val outputDir = if (extractHere) {
            extractTo
        } else {
            File(extractTo, zipFile.nameWithoutExtension)
        }

        ZipFile(zipFile).use { zip ->
            zip.entries().asSequence().forEach { entry ->
                zip.getInputStream(entry).use { input ->
                    if (entry.isDirectory) {
                        val d = File(outputDir, entry.name)
                        if (!d.exists()) d.mkdirs()
                    } else {
                        val f = File(outputDir, entry.name)
                        if (f.parentFile?.exists() != true)  f.parentFile?.mkdirs()

                        f.outputStream().use { output ->
                            input.copyTo(output)
                        }
                    }
                }
            }
        }

        extractTo
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

Upvotes: 1

this code is for unziping from Assets

1.for unzping first u need InputStream
2.put it in ZipInputStream
3.if directory is not exist u have to make by .mkdirs()

private val BUFFER_SIZE = 8192//2048;

private val SDPath = Environment.getExternalStorageDirectory().absolutePath
private val unzipPath = "$SDPath/temp/zipunzipFile/unzip/"
var count: Int
    val buffer = ByteArray(BUFFER_SIZE)


    val context: Context = this
    val am = context.getAssets()
    val stream = context.getAssets().open("raw.zip")
 try {
 ZipInputStream(stream).use { zis ->
    var ze: ZipEntry
    while (zis.nextEntry.also { ze = it } != null) {
        var fileName = ze.name
        fileName = fileName.substring(fileName.indexOf("/") + 1)
        val file = File(unzipPath, fileName)
        val dir = if (ze.isDirectory) file else file.getParentFile()

        if (!dir.isDirectory() && !dir.mkdirs())
            throw FileNotFoundException("Invalid path: " + dir.getAbsolutePath())
        if (ze.isDirectory) continue
        val fout = FileOutputStream(file)
        try {
            while ( zis.read(buffer).also { count = it } != -1)
                fout.write(buffer, 0, count)
        } finally {

   val fout : FileOutputStream =openFileOutput(fileName, Context.MODE_PRIVATE)

            fout.close()
        }

    }

for unziping from externalStorage:

private val sourceFile= "$SDPath/unzipFile/data/"

ZipInputStream zis = null;

    try {
        zis = new ZipInputStream(new BufferedInputStream(new 
 FileInputStream(sourceFile)));
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((ze = zis.getNextEntry()) != null) {
            String fileName = ze.getName();
            fileName = fileName.substring(fileName.indexOf("/") + 1);
            File file = new File(destinationFolder, fileName);
            File dir = ze.isDirectory() ? file : file.getParentFile();

            if (!dir.isDirectory() && !dir.mkdirs())
                throw new FileNotFoundException("Invalid path: " + 
  dir.getAbsolutePath());
            if (ze.isDirectory()) continue;
            FileOutputStream fout = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1)
                    fout.write(buffer, 0, count);
            } finally {
                fout.close();
            }

        }
    } catch (IOException ioe) {
        Log.d(TAG, ioe.getMessage());
        return false;
    } finally {
        if (zis != null)
            try {
                zis.close();
            } catch (IOException e) {

            }
    }
    return true;

Upvotes: 1

Roman  Elizarov
Roman Elizarov

Reputation: 28678

The easiest way is to just use exec unzip (assuming that the name of your zip file is stored in zipFileName variable):

ProcessBuilder()
    .command("unzip", zipFileName)
    .redirectError(ProcessBuilder.Redirect.INHERIT)
    .redirectOutput(ProcessBuilder.Redirect.INHERIT)
    .start()
    .waitFor()

The different approach, that is more portable (it will run on any OS and does not require unzip executable to be present), but somewhat less feature-full (it will not restore Unix permissions), is to do unzipping in code:

import java.io.File
import java.util.zip.ZipFile

ZipFile(zipFileName).use { zip ->
    zip.entries().asSequence().forEach { entry ->
        zip.getInputStream(entry).use { input ->
            File(entry.name).outputStream().use { output ->
                input.copyTo(output)
            }
        }
    }
}

If you need to scan all *.zip file, then you can do it like this:

File(".").list { _, name -> name.endsWith(".zip") }?.forEach { zipFileName ->
    // any of the above approaches        
}

or like this:

import java.nio.file.*

Files.newDirectoryStream(Paths.get("."), "*.zip").forEach { path ->
    val zipFileName = path.toString()
    // any of the above approaches        
}

Upvotes: 26

Related Questions