Created
September 1, 2023 21:45
-
-
Save OndraZizka/75a1b38c95a85c1e0a0eaa2462ad22bb to your computer and use it in GitHub Desktop.
Kotlin - utilities for loading resources from the classpath.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileNotFoundException | |
import java.io.InputStream | |
import java.nio.file.Path | |
object ResourceUtils { | |
fun getCallingClassName(): String? { | |
var testUtilsSpotted = false; | |
for (stackItem in Thread.currentThread().stackTrace) { | |
if (stackItem.className == ResourceUtils::class.java.name) { | |
testUtilsSpotted = true | |
continue | |
} else if (testUtilsSpotted) { | |
return stackItem.className | |
} | |
} | |
return null | |
} | |
fun getResourceFullPathFromRelative(resourcePathFromCallingClass: String, fqcn: String): Path { | |
val packageClassPath = Path.of(fqcn.replace('.', '/')).parent | |
return packageClassPath.resolve(Path.of(resourcePathFromCallingClass).normalize()) | |
} | |
fun openResourceAtRelativePath(resourcePath: Path): InputStream { | |
val path = getResourceFullPathFromRelative(resourcePath.toString(), getCallingClassName() ?: throw IllegalStateException("Can't find calling class.")) | |
return javaClass.classLoader!!.getResourceAsStream(path.toString()) | |
?: throw FileNotFoundException("Resource '$path' not found in the classpath.") | |
} | |
fun loadResourceAtRelativePath(resourcePath: Path): String { | |
val inputStream = openResourceAtRelativePath(resourcePath) | |
return inputStream.use { it.reader().readText() } | |
} | |
fun loadResourceAtRelativePath(resourcePath: String) = loadResourceAtRelativePath(Path.of(resourcePath)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment