How to read a text file from resources in Kotlin?

后端 未结 10 562
心在旅途
心在旅途 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:40
    val fileContent = javaClass.getResource("/html/file.html").readText()
    
    0 讨论(0)
  • 2020-12-08 18:41

    This is the way that I prefer to do it:

    fun getResourceText(path: String): String {
        return File(ClassLoader.getSystemResource(path).file).readText()
    }
    
    0 讨论(0)
  • 2020-12-08 18:42
    private fun loadResource(file: String) = {}::class.java.getResource(file).readText()
    
    0 讨论(0)
  • 2020-12-08 18:53

    You might find the File class useful:

    import java.io.File
    
    fun main(args: Array<String>) {
      val content = File("src/main/resources/input.txt").readText()
      print(content)
    } 
    
    0 讨论(0)
提交回复
热议问题