Skip to content

Instantly share code, notes, and snippets.

@gaerfield
Last active March 27, 2020 16:50
Show Gist options
  • Save gaerfield/e3cd636c407f61f0322dab115aef7f1e to your computer and use it in GitHub Desktop.
Save gaerfield/e3cd636c407f61f0322dab115aef7f1e to your computer and use it in GitHub Desktop.
I hate working with resources in Java or Kotlin. The idea if resources is good, but loading them is unbelievable error-prone ... every time. This one makes it a little easier. It just looks for the given file or path according to the package-path of the class.
import java.io.File
import kotlin.reflect.KClass
object Resources {
/**
* Loads a resource from within the resources-Folder (usually src/main/resources):
* ```
* val resource : File = this::class.resourceFile("myResource.xml")
* ```
*/
@Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
fun <K : Any> file(clazz: KClass<K>, path: String): File {
return File(clazz.java.classLoader.getResource(path).file)
}
fun <K : Any> lines(clazz: KClass<K>, path: String) = file(clazz, path).reader().readLines()
fun <K : Any> content(clazz: KClass<K>, path: String) = file(clazz, path).reader().readText()
}
/**
* Loads a resource within the package-structure of the current class. If the class full qualified-name is
* `org.acme.ResourceLoader`, then the following code will try to load `org/acme/myResource.xml` from within the
* resources-Folder (usually src/main/resources):
* ```
* val resource : File = this::class.resourceFile("myResource.xml")
* ```
*/
fun <T : Any> KClass<T>.resourceFile(file: String) =
Resources.file(this, this.qualifiedName?.substringBeforeLast('.')?.replace('.','/')+"/"+file)
fun <T : Any> KClass<T>.resourceContent(file: String) = resourceFile(file).reader().readText()
fun <T : Any> KClass<T>.resourceLines(file: String) = resourceFile(file).reader().readText()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment