How to read a text file from resources in Kotlin?

后端 未结 10 575
心在旅途
心在旅途 2020-12-08 17:59

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({         


        
10条回答
  •  悲哀的现实
    2020-12-08 18:30

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

提交回复
热议问题