Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file from resources in Kotlin?

Tags:

kotlin

People also ask

How do I read a text file in Kotlin?

1) Select "Project" from the top of the vertical toolbar to open the project "tool window" 2) From the drop-down menu at the top of the "tool window", select "Android" 3) Right-click on "App" and select "New" then -> "Folder" (the one with the green Android icon beside it) then -> "Assets Folder" 4) Right-click on the ...

How do I get a file from Kotlin?

Get File Extension in Kotlin Kotlin – Get File Extension : In Kotlin, to extract or get the file extension, use File. extension property. File. extension is a String value.

How do I read Kotlin properties file?

Read values from properties filegetProperties() and then list out all system properties using the stringPropertyNames() function. Here's how you can load properties from the property file present on the file system. That's all about reading and writing values to the properties file in Kotlin.


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

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")

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

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

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

private fun loadResource(file: String) = {}::class.java.getResource(file).readText()