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

问题描述 投票:2回答:1

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

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

unzip *.zip

有没有一种很好的方法来解压缩kotlin脚本中的文件?

bash kotlin unzip
1个回答
8
投票

最简单的方法是使用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        
}
© www.soinside.com 2019 - 2024. All rights reserved.