Search code examples
kotlinfile-ioclasspathclassloader

How to read a text file from resources in Kotlin?


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

class MySpec : Spek(
    {
        describe("blah blah") {
            given("blah blah") {
                var fileContent: String = ""
                beforeEachTest {
                    // How to read the file.html in src/test/resources/html/
                    fileContent = ...
                }
                it("should blah blah") {
                    ...
                }
            }
        }
    }
)

Solution

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