Skip to content

Instantly share code, notes, and snippets.

@george-hawkins
Last active June 11, 2018 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save george-hawkins/90a278d02abefc613058a884a8e2e97e to your computer and use it in GitHub Desktop.
Save george-hawkins/90a278d02abefc613058a884a8e2e97e to your computer and use it in GitHub Desktop.
Generic logic to walk both jar and filesystem isn't simple...
package com.example
import org.junit.Test
import java.net.URI
import java.net.URL
import java.nio.file.FileSystem
import java.nio.file.FileSystemNotFoundException
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Paths
class FooBar {
@Test
fun `test walk`() {
fun dump(fs: FileSystem, uri: URI) = Files.walk(fs.provider().getPath(uri)).forEach(::println)
// Filesystem walking...
run {
val cwd = Paths.get("")
val uri = cwd.toUri()
val fs = cwd.fileSystem
println(uri.path)
dump(fs, uri)
}
// You might imagine the URI above could be used in the logic below but for some reason the path
// component of the URI passed to FileSystems.getFileSystem(uri) must be "/" if the scheme is "file"
// but not if it's "jar". So it seems you can't easily write a scheme agnostic solution :(
// Jar walking...
run {
val pkg = URL("jar:file:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar!/java/lang")
val uri = pkg.toURI()
val fs = try {
FileSystems.getFileSystem(uri)
} catch (e: FileSystemNotFoundException) {
FileSystems.newFileSystem(uri, mapOf<String, Any>())
}
println(uri.path)
dump(fs, uri)
}
// Note that there's no easy way to get a URL for a package rather than a class.
println(this.javaClass.getResource("/java/lang/String.class"))
// The above is fine but the following all return null:
println(this.javaClass.getResource("/java/lang/"))
println(this.javaClass.getResource("/java/lang"))
println(this.javaClass.getResource("java/lang/"))
println(this.javaClass.getResource("java/lang"))
println(this.javaClass.classLoader.getResource("/java/lang/"))
println(this.javaClass.classLoader.getResource("/java/lang"))
println(this.javaClass.classLoader.getResource("java/lang/"))
println(this.javaClass.classLoader.getResource("java/lang"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment