用kotlin脚本解压缩文件[.kts]

时间:2017-10-08 03:53:23

标签: bash kotlin unzip

我正在考虑用kotlin脚本重写一些现有的bash脚本。

其中一个脚本有一个解压缩目录中所有文件的部分。在bash:

unzip *.zip

有一种很好的方法可以在kotlin脚本中解压缩文件吗?

2 个答案:

答案 0 :(得分:10)

最简单的方法是使用exec unzip(假设您的zip文件的名称存储在zipFileName变量中):

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

不同的方法,更便携(它可以在任何操作系统上运行,并且不需要unzip可执行文件),但功能较少(它不会恢复Unix权限),是在代码中解压缩:

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)
            }
        }
    }
}

如果您需要扫描所有*.zip文件,那么您可以这样做:

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

或者像这样:

import java.nio.file.*

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

答案 1 :(得分:0)

此代码用于从 资产

解压缩

1。要先解压缩,您需要InputStream
2.将其放入ZipInputStream
3.如果目录不存在,则必须按.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()
        }

    }

用于从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;