Подтвердить что ты не робот

Как читать текстовый файл из ресурсов в Котлин?

Я хочу написать тест Spek в Котлине. Тест должен прочитать HTML файл из папки src/test/resources. Как это сделать?

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

Ответ 1

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

Ответ 2

другое немного другое решение:

@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)
}

Ответ 3

Несколько другое решение:

class MySpec : Spek({
    describe("blah blah") {
        given("blah blah") {

            var fileContent = ""

            beforeEachTest {
                html = this.javaClass.getResource("/html/file.html").readText()
            }

            it("should blah blah") {
                ...
            }
        }
    }
})

Ответ 4

Не знаю, почему это так сложно, но самый простой способ, который я нашел (без необходимости ссылаться на определенный класс):

fun getResourceAsText(path: String): String {
    return object {}.javaClass.getResource(path).readText()
}

А затем передать абсолютный URL, например,

val html = getResourceAsText("/www/index.html")

Ответ 5

Котлин + Весенний путь:

@Autowired
private lateinit var resourceLoader: ResourceLoader

fun load() {
    val html = resourceLoader.getResource("classpath:html/file.html").file
        .readText(charset = Charsets.UTF_8)
}

Ответ 6

val fileContent = javaClass.getResource("/html/file.html").readText()

Ответ 7

Вы можете найти класс File полезным:

import java.io.File

fun main(args: Array<String>) {
  val content = File("src/main/resources/input.txt").readText()
  print(content)
} 

Ответ 8

Использование ресурсов библиотеки Google Guava:

import com.google.common.io.Resources;

val fileContent: String = Resources.getResource("/html/file.html").readText()