How to read a text file from resources in Kotlin?

Olaf picture Olaf · Mar 11, 2017 · Viewed 73k times · Source

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

Answer

JB Nizet picture JB Nizet · Mar 11, 2017
val fileContent = MySpec::class.java.getResource("/html/file.html").readText()