Kotlin read resource file

Kotlin read file tutorial

Kotlin read file tutorial shows how to read a file in Kotlin. We show several ways of reading a file in Kotlin.

In this tutorial, we use the File methods to read files.

The tutorial presents five examples that read a file in Kotlin.

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

In the examples, we use this text file.

Kotlin read file with File.readLines

File.readLines reads the file content as a list of lines. It should not be used for large files.

package com.zetcode import java.io.File fun main() < val fileName = "src/resources/thermopylae.txt" val lines: List= File(fileName).readLines() lines.forEach < line ->println(line) > >

The example reads a file with File.readLines .

Kotlin read file with File.useLines

File.useLines reads all data as a list of lines and provides it to the callback. It closes the reader in the end.

package com.zetcode import java.io.File fun main() < val fileName = "src/resources/thermopylae.txt" val myList = mutableListOf() File(fileName).useLines < lines ->myList.addAll(lines) > myList.forEachIndexed < i, line ->println("$: " + line) > >

The example reads a file and prints it to the console. We add line numbers to the output.

val myList = mutableListOf()

A mutable list is created.

File(fileName).useLines < lines ->myList.addAll(lines) >

With File.useLines we copy the list of the lines into the above created mutable list.

myList.forEachIndexed < i, line ->println("$: " + line) >

With forEachIndexed we add a line number to each line.

Kotlin read file with File.readText

File.readText gets the entire content of this file as a String . It is not recommended to use this method on huge files.

package com.zetcode import java.io.File fun main() < val fileName = "src/resources/thermopylae.txt" val content = File(fileName).readText() println(content) >

In the example, we read the whole file into a string and print it to the console.

Kotlin read file with InputStream

InputStream is an input stream of bytes.

package com.zetcode import java.io.File import java.io.InputStream import java.nio.charset.Charset fun main() < val fileName = "src/resources/thermopylae.txt" val myFile = File(fileName) var ins: InputStream = myFile.inputStream() var content = ins.readBytes().toString(Charset.defaultCharset()) println(content) >

The example creates an InputStream from a File and reads bytes from it. The bytes are transformed into text.

var ins: InputStream = myFile.inputStream()

An InputStream is created from a File with inputStream .

var content = ins.readBytes().toString(Charset.defaultCharset())

We read bytes from the InputStream with readBytes and transform the bytes into text with toString .

Kotlin read file with readBytes

The readBytes reads the entire content of a file as a byte array. It is not recommended on huge files.

package com.zetcode import java.io.File fun main() < val fileName = "src/resources/thermopylae.txt" val file = File(fileName) var bytes: ByteArray = file.readBytes() bytes.forEachIndexed < i, byte ->( if (i == 0) < print("$") > else if (i % 10 == 0) < print("$\n") > else < print("$") >) > >

The example reads a text file into a byte array. It prints the file as numbers to the console.

In this tutorial, we have shown how to read file in Kotlin.

Источник

Чтение ресурсных файлов

Помимо конфигурационных файлов в приложении бывает удобно хранить и некоторые другие файлы ресурсов. Например, тексты или изображения. Достаточно положить эти файлы в папку resources вашего проекта и в процессе выполнения вы сможете получить к ним доступ.

Например, нам нужно прочитать файл test.txt. Положим его в папку resources вашего проекта (она есть и в maven, и в gradle). Важно положить именно в ту resources, которая относится к самому приложению, а не к тестам, иначе вы не сможете обратиться к файлу.

public class ResourceReader <

public static void main(String[] args) throws Exception var example = new ResourceReader();
var content = example.readTextResource( «test.txt» );
System.out.println(content);
>

public String readTextResource(String filename) throws Exception var uri = getClass().getResource(String.format( «/%s» , filename)).toURI();
return Files.readString(Paths.get(uri));
>
>

Доступ к ресурсам мы получаем через метод getResource(), который имеется у объекта Class. Но доступ к классу из статичного контекста метода main() получить нельзя, поэтому мы сначала создаём экземпляр класса, а затем внутри него уже обращаемся к ресурсу. Обратите внимание, что имя ресурса начинается со слеша. Путь до ресурса указывается от корня папки resources. Для чтения содержимого файла целиком в строку используем метод Files.readString(), появившийся в Java 11. Если у вас более ранняя версия Java, то данный метод будет недоступен. В случае, если файл будет очень большим, также лучше данный метод не использовать, а читать файл с помощью буферизованного потока.

То же самое на kotlin:

fun main() <
val example = ResourceReader()
val content = example.readTextResource( «test.txt» )
println(content)
>

class ResourceReader fun readTextResource(filename: String): String val uri = this .javaClass.getResource( «/$filename» ).toURI()
return Files.readString(Paths.get(uri))
>
>

Ожидаемо, что код на kotlin более компактный.

Источник

How to read a text file from resources without javaClass

I need to read a text file with readLines() and I’ve already found this question, but the code in the answers always uses some variation of javaClass ; it seems to work only inside a class, while I’m using just a simple Kotlin file with no declared classes. Writing it like this is correct syntax-wise but it looks really ugly and it always returns null , so it must be wrong:

val lines = object <>.javaClass.getResource("file.txt")?.toURI()?.toPath()?.readLines() 
val lines = File("src/main/resources/file.txt").readLines() 

My guess is that you get null because of toURI()?.toPath() which wasn’t present in the answers linked by you. file.txt does not exist anywhere in the filesystem and can’t be accessed like a file. And I think object <> approach is just fine. Alternatively, you can use just any class from your module.

4 Answers 4

Thanks to this answer for providing the correct way to read the file. Currently, reading files from resources without using javaClass or similar constructs doesn’t seem to be possible.

// use this if you're inside a class val lines = this::class.java.getResourceAsStream("file.txt")?.bufferedReader()?.readLines() // use this otherwise val lines = object <>.javaClass.getResourceAsStream("file.txt")?.bufferedReader()?.readLines() 

According to other similar questions I’ve found, the second way might also work within a lambda but I haven’t tested it. Notice the need for the ?. operator and the lines?.let <> syntax needed from this point onward, because getResourceAsStream() returns null if no resource is found with the given name.

Indeed, using object <> is a good workaround for when you’re not inside a class. Btw if you’re wondering whether you should use javaclass or class.java , see stackoverflow.com/questions/46674787/…

This worked for me after I did /file.txt i.e. val lines = object <>.javaClass.getResourceAsStream(«/file.txt»)?.bufferedReader()?.readLines() otherwise it was returning null

Kotlin doesn’t have its own means of getting a resource, so you have to use Java’s method Class.getResource . You should not assume that the resource is a file (i.e. don’t use toPath ) as it could well be an entry in a jar, and not a file on the file system. To read a resource, it is easier to get the resource as an InputStream and then read lines from it:

val lines = this::class.java.getResourceAsStream("file.txt").bufferedReader().readLines() 

Thank you, it worked. I’m adding my own answer with the version that uses object <>.javaClass which is needed in my case.

I’m not sure if my response attempts to answer your exact question, but perhaps you could do something like this:

I’m guessing in the final use case, the file names would be dynamic — Not statically declared. In which case, if you have access to or know the path to the folder, you could do something like this:

 // Create an extension function on the String class to retrieve a list of // files available within a folder. Though I have not added a check here // to validate this, a condition can be added to assert if the extension // called is executed on a folder or not fun String.getFilesInFolder(): Array? = with(File(this)) < return listFiles() >// Call the extension function on the String folder path wherever required fun retrieveFiles(): Array? = [PATH TO FOLDER].getFilesInFolder() 

Once you have a reference to the List object, you could do something like this:

 // Create an extension function to read fun File.retrieveContent() = readLines() // You can can further expand this use case to conditionally return // readLines() or entire file data using a buffered reader or convert file // content to a Data class through GSON/whatever. // You can use Generic Constraints // Refer this article for possibilities // https://kotlinlang.org/docs/generics.html#generic-constraints // Then simply call this extension function after retrieving files in the folder. listOfFiles?.forEach < singleFile ->println(singleFile.retrieveContent()) > 

Источник

How to read a text file from resources in Kotlin?

In this article, we will see how we can read a text file using Kotlin library functions. Kotlin is based on Java, hence we can use different Java library functions in Kotlin too.

Example — BufferedReader

Go ahead and create a Kotlin file in your workspace and name it » ReadFile.kt«. Keep a text file with some data in the same directory. For this example, our Text file looks like this −

Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin

Execute the following piece of code to read the above text file.

// importing java library function // to read files from different sources import java.io.File import java.io.BufferedReader fun main(args: Array) < val bufferedReader: BufferedReader = File("Text.txt").bufferedReader() val inputString = bufferedReader.use < it.readText() >println(inputString) >

Output

The above program will read the text file in the same directory and give us the following output

Running] cd ">" && kotlinc readFile.kt -include-runtime -d readFile.jar && java -jar readFile.jar Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin

Example — InputStream

File information can be read using another library function, that is, InputStream. In the following example, we will read the same text file using InputStream.

import java.io.File import java.io.InputStream fun main(args: Array) < val inputStream: InputStream = File("Text.txt").inputStream() val inputString = inputStream.bufferedReader().use < it.readText() >println(inputString) >

Output

It will produce the following output

[Running] cd ">" && kotlinc readFile.kt -include-runtime -d readFile.jar && java -jar readFile.jar Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin

Источник

How to read a text file from resources in Kotlin?

For me both these options worked in an Android app (notice the extra / in one of them, which has to be removed in the other): this::class.java.getResource(«/html/file.html»).readText() and this::class.java.classLoader.getResource(«html/file.html»).‌​readText()

Oddly enough I always need a leading slash. E.g if the file is in the resources root directory, you still have to refer to it as «/file.html»

I couldn’t get this to work until I read here the difference between getResource and classLoader.getResource : stackoverflow.com/a/6608848/3519951 @SomaiahKumbera leading slash makes the path absolute, see linked post.

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? = object <>.javaClass.getResource(path)?.readText() 

It returns null if no resource with this name is found (as documented).

And then passing in an absolute URL, e.g.

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

javaClass must be called on an object according to the docs kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-class.html If it works without then go for ya life 🙂

One downside with the method above is it creates a new object for every resource access. Would be better to store the dummy object outside the function.

@RussellBriggs tbh I don’t think that matters much. The performance of an object creation is not really an issue if you do disk access!

another slightly different solution:

@Test fun basicTest() < "/html/file.html".asResource < // test on `it` here. println(it) >> fun String.asResource(work: (String) -> Unit)

Nice usage of an extension function! But why do you use a lambda function here? That does not make much sense to me. Furthermore, the this part did not work for me. Thus I recommend the following: fun String.asResource(): URL? = object <>.javaClass.getResource(this)

I like this method of working on it where you declare the file, then work on the contents of that file. Personal preference I guess. this in the example above refers to the string object.

it is in this context. i wouldn’t make this globally available or use it outside of test classes. I consider it more of a mapping function here.

@Ben Use of extension functions and extension properties is by definition an abuse, since it pretends to add members to a class it doesn’t have internal access to. If you don’t like it, don’t use it. Some of us are focused on making our code more straightforward rather than worrying about OO purity.

Источник

Читайте также:  Java openjdk windows downloads
Оцените статью