How to read a text file from resources in Kotlin?

Solution 1:

val fileContent = MySpec::class.java.getResource("/html/file.html").readText()

Solution 2:

No idea why this is so hard, but the simplest way I've found (without having to refer to a particular class) is:

fun getResourceAsText(path: String): String? =
    object {}.javaClass.getResource(path)?.readText()

It returns null if no resource with this name is found (as documented).

And then passing in an absolute URL, e.g.

val html = getResourceAsText("/www/index.html")!!

Solution 3:

another slightly different solution:

@Test
fun basicTest() {
    "/html/file.html".asResource {
        // test on `it` here...
        println(it)
    }

}

fun String.asResource(work: (String) -> Unit) {
    val content = this.javaClass::class.java.getResource(this).readText()
    work(content)
}

Solution 4:

A slightly different solution:

class MySpec : Spek({
    describe("blah blah") {
        given("blah blah") {

            var fileContent = ""

            beforeEachTest {
                html = this.javaClass.getResource("/html/file.html").readText()
            }

            it("should blah blah") {
                ...
            }
        }
    }
})