Skip to content

Instantly share code, notes, and snippets.

@pentiumao
Last active December 18, 2019 15:54
Show Gist options
  • Save pentiumao/f6ddca4087760362acf5cdccfaba34f7 to your computer and use it in GitHub Desktop.
Save pentiumao/f6ddca4087760362acf5cdccfaba34f7 to your computer and use it in GitHub Desktop.
Zip File System Provider
/**
* Kotlin version: 1.3.61
* JVM target: 1.8
* @param source the path to the file to copy
* @param target the path to the target file
* @param env a map of provider specific properties to configure the file system
* @see https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html
*/
fun archive(
source: Path,
target: Path,
env: Map<String, String> = mapOf("create" to "true", "encoding" to "UTF-8")
) {
val targetFile = target.toFile().let {
if (it.isDirectory) {
// target is directory, should generate the file name with source
return@let File(it, "${source.fileName}.zip")
}
return@let it
}
// create the new zip file system
val zipUri = URI.create("jar:file:${targetFile.absolutePath}")
FileSystems.newFileSystem(zipUri, env).use { fs ->
traverse(fs, source.parent, source)
}
}
/**
* Archive file recursively
*/
private fun traverse(fs: FileSystem, root: Path, source: Path) {
val relativePath = root.relativize(source)
val target = fs.getPath(relativePath.toString())
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
source.toFile().takeIf {
it.isDirectory
}?.listFiles()?.forEach { child ->
traverse(fs, root, child.toPath())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment