What's the intended way to read a resource file?

I have a text file in the resources directory and I want to read it. Currently, I’ve managed to do it in the following ways:

// specifying the full path
val lines = File("src/main/resources/other_subdirectories/file.txt").readLines()

// only works inside a class
val lines = this::class.java.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()

// works otherwise
val lines = object {}.javaClass.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()

Admittedly, none of the three ways looks perfect and I’m wondering if there’s something I’m missing, or maybe if a better workaround is already planned. You can also refer to this SO question I’ve posted earlier.

1 Like

fwiw I use the last one.
It’s rather ugly.

1 Like

Don’t use the first - this is not the correct way of getting resources in Java/Kotlin. Resources are streams of data, not files. Build your application/library into jar, apk or whatever your project is, re-run the above code and you will see it won’t work. Other two options should be fine.

4 Likes