解压缩kotlin脚本中的文件

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

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

unzip *.zip 

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

最简单的方法是使用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 } 
Interesting Posts