Skip to content

Instantly share code, notes, and snippets.

@rock3r
Created July 7, 2023 13:46
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 rock3r/5b3b5519da7b4e58b4b25579150756b0 to your computer and use it in GitHub Desktop.
Save rock3r/5b3b5519da7b4e58b4b25579150756b0 to your computer and use it in GitHub Desktop.
JVM (Desktop) resource loading, for resources living in a different classloader
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Sebastiano Poggi wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Seb
* ----------------------------------------------------------------------------
*/
/**
* Load a resource from a given class' classpath, given its path.
* Note: you will need to customise the [MyClass] referenced in there
* to any class living in the same classloader as the target resource.
*/
fun load(resourcePath: String): InputStream {
val normalizedPath = if (!resourcePath.startsWith("/")) "/$resourcePath" else resourcePath
val resource = MyClass::class.java.getResourceAsStream(normalizedPath)
return requireNotNull(resource) { "Resource $resourcePath not found" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment