How to read a text file from resources in Kotlin?

后端 未结 10 561
心在旅途
心在旅途 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:26

    Kotlin + Spring way:

    @Autowired
    private lateinit var resourceLoader: ResourceLoader
    
    fun load() {
        val html = resourceLoader.getResource("classpath:html/file.html").file
            .readText(charset = Charsets.UTF_8)
    }
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2020-12-08 18:31

    Using Google Guava library Resources class:

    import com.google.common.io.Resources;
    
    val fileContent: String = Resources.getResource("/html/file.html").readText()
    
    0 讨论(0)
  • 2020-12-08 18:33

    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") {
                    ...
                }
            }
        }
    })
    
    0 讨论(0)
  • 2020-12-08 18:37
    val fileContent = MySpec::class.java.getResource("/html/file.html").readText()
    
    0 讨论(0)
  • 2020-12-08 18:39

    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)
    }
    
    0 讨论(0)
提交回复
热议问题