How to read a text file from resources in Kotlin?

2019-02-11 10:49发布

问题:

I want to write a Spek test in Kotlin. The test should read an HTML file from the src/test/resources folder. How to do it?

class MySpec : Spek({

    describe("blah blah") {

        given("blah blah") {

            var fileContent : String = ""

            beforeEachTest {
                // How to read the file file.html in src/test/resources/html
                fileContent = ...  
            }

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

回答1:

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


回答2:

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)
}


回答3:

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") {
                ...
            }
        }
    }
})


回答4:

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 {
    return object {}.javaClass.getResource(path).readText()
}

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

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


标签: kotlin