Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unzip a file in kotlin script [.kts]

Tags:

bash

kotlin

unzip

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?

like image 301
triad Avatar asked Oct 08 '17 03:10

triad


People also ask

How do I unzip a data file?

To unzip filesOpen File Explorer and find the zipped folder. To unzip the entire folder, right-click to select Extract All, and then follow the instructions. To unzip a single file or folder, double-click the zipped folder to open it. Then, drag or copy the item from the zipped folder to a new location.

How do I unzip a script in Linux?

You can use the unzip or tar command to extract (unzip) the file on Linux or Unix-like operating system. Unzip is a program to unpack, list, test, and compressed (extract) files and it may not be installed by default.


2 Answers

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        
}
like image 59
Roman Elizarov Avatar answered Sep 21 '22 17:09

Roman Elizarov


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;
like image 27
android remote control Avatar answered Sep 20 '22 17:09

android remote control