Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

494
Views
¿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 answers
Answer question

0

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

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 Report

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 Report

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 Report

0

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

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 Report

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 Report

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 Report

0

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

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!