Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

487
Visualizações
¿Cómo leer un archivo de texto de recursos en Kotlin?

Quiero escribir una prueba Spek en Kotlin. La prueba debe leer un archivo HTML de la carpeta src/test/resources . ¿Cómo hacerlo?

 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") { ... } } } })
over 4 years ago · Santiago Trujillo
12 Respostas
Responde à pergunta

0

val fileContent = MySpec::class.java.getResource("/html/file.html").readText()
over 4 years ago · Santiago Trujillo Relatório

0

Una solución ligeramente diferente:

 class MySpec : Spek({ describe("blah blah") { given("blah blah") { var fileContent = "" beforeEachTest { html = this.javaClass.getResource("/html/file.html").readText() } it("should blah blah") { ... } } } })
over 4 years ago · Santiago Trujillo Relatório

0

otra solución ligeramente diferente:

 @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) }
over 4 years ago · Santiago Trujillo Relatório

0

No tengo idea de por qué esto es tan difícil, pero la forma más sencilla que he encontrado (sin tener que referirme a una clase en particular) es:

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

Devuelve null si no se encuentra ningún recurso con este nombre ( como se documenta ).

Y luego pasar una URL absoluta, por ejemplo

 val html = getResourceAsText("/www/index.html")!!
over 4 years ago · Santiago Trujillo Relatório

0

val fileContent = javaClass.getResource("/html/file.html").readText()
over 4 years ago · Santiago Trujillo Relatório

0

Kotlin + Manera de primavera:

 @Autowired private lateinit var resourceLoader: ResourceLoader fun load() { val html = resourceLoader.getResource("classpath:html/file.html").file .readText(charset = Charsets.UTF_8) }
over 4 years ago · Santiago Trujillo Relatório

0

Puede encontrar útil la clase File:

 import java.io.File fun main(args: Array<String>) { val content = File("src/main/resources/input.txt").readText() print(content) }
over 4 years ago · Santiago Trujillo Relatório

0

Uso de la clase de recursos de la biblioteca de guayaba de Google:

 import com.google.common.io.Resources; val fileContent: String = Resources.getResource("/html/file.html").readText()
over 4 years ago · Santiago Trujillo Relatório

0

private fun loadResource(file: String) = {}::class.java.getResource(file).readText()
over 4 years ago · Santiago Trujillo Relatório

0

Esta es la forma en que yo prefiero hacerlo:

 fun getResourceText(path: String): String { return File(ClassLoader.getSystemResource(path).file).readText() }
over 4 years ago · Santiago Trujillo Relatório

0

esta función de kotlin de nivel superior hará el trabajo en cualquier caso

 fun loadResource(path: String): URL { return Thread.currentThread().contextClassLoader.getResource(path) }

o si quieres una función más robusta

 fun loadResource(path: String): URL { val resource = Thread.currentThread().contextClassLoader.getResource(path) requireNotNull(resource) { "Resource $path not found" } return resource }
over 4 years ago · Santiago Trujillo Relatório

0

FYI: En todos los casos anteriores. getResource() es una forma insegura de usar anulable.

No lo he probado localmente, pero prefiero de esta manera:

 fun readFile(resourcePath: String) = String::class.java.getResource(resourcePath)?.readText() ?: "<handle default. or handle custom exception>"

O incluso como función de tipo de datos personalizado

 private fun String.asResource() = this::class.java.getResource(resourcePath)?.readText() ?: "<handle default. or handle custom exception>"

y luego puede llamar directamente en la ruta como:

 // For suppose val path = "/src/test/resources" val content = path.asResource()
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda