Kotlin read from file

Different ways to read the content of a file in Kotlin

We have a couple of different ways to read the file content in Kotlin. For these examples, we have created one readme.md file with the below content :

.com programming tutorial and examples 

Each example will read the content from this file and print it out.

You can place it on anywhere you want. Just update the path variable in the below examples.

readLines is not for large files. You can use it to read the contents of small files. It returns the file content as a list of lines.

By default, it uses UTF-8, but you can specify a different charset as its argument.

import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val fileContent: Liststring> = File(filePath).readLines() fileContent.forEach  println(it) > > 

This example reads the content of readme.md file and put that in the list fileContent. Each line is a new list element. The forEach loop will print each line of the file on a new line.

It reads the file content and calls one callback function with a sequence of all content. Once the processing is done, it closes the reader.

By default, it uses UTF-8, but you can specify a different charset as its argument.

import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val fileContent = mutableListOfstring>() File(filePath).useLines  lines -> fileContent.addAll(lines) > print(fileContent) >

Here, we are reading the content of the file to fileContent, a mutable list of string. This program will print the below output :

[codevscolor.com, programming tutorial, and, examples] 

readText() reads the entire content of the file as a string. By default, it uses UTF-8, but you can specify a different charset as its argument.

This method is not recommended for large files.

import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val fileContent = File(filePath).readText() print(fileContent) > 
.com programming tutorial and examples 

reader methods returns one InputStreamReader. This can be used to read the contents of a file with a while loop :

import java.io.File import java.io.InputStreamReader fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val fileReader: InputStreamReader = File(filePath).reader() var i: Int = fileReader.read() while (i != -1)  print(i.toChar()) i = fileReader.read() > > 

The read() method of InputStreamReader reads the content from a stream as integer. toChar() converts it to character.

.com programming tutorial and examples 

inputStream() method returns one input stream and we can read the contents as bytes and convert it to string :

import java.io.File import java.io.InputStream import java.nio.charset.Charset fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val fileReader: InputStream = File(filePath).inputStream() val fileContent = fileReader.readBytes().toString(Charset.defaultCharset()) println(fileContent) > 

readBytes() reads the content as a byte array. toString converts it to a string.

.com programming tutorial and examples 

forEachLine reads the content of a file. It reads the content using specified charset. The default charset is UTF-8. We can access each line using it.

import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" File(filePath).forEachLine  println(it) > > 

BufferedReader is another way to read the content of a file :

import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/readme.md" val content = File(filePath).bufferedReader().readLines() print(content) > 

bufferedReader() returns one buffered reader and readLines() returns one list of strings.

Источник

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.

Источник

How to read a file in Kotlin

In this tutorial, we are going to present several ways to read a file in Kotlin. Kotlin is a cross-platform, general-purpose programming language that is becoming more and more popular since it is now the preferred language for Android app development.

2. Create a file

First, let’s create a file for testing purposes with a name frontbackend.txt and the following content:

Tutorials: - one - two - three 

We can do it using the touch command on Linux or with a Notepad on Windows. For a sake of simplicity let’s put it into a folder with our sample Kotlin files.

3. Read a file using InputStream

3.1. Read all lines at once

The first approach use BufferedReader and use method:

import java.io.File import java.io.InputStream fun main(args: Array) < val inputStream: InputStream = File("frontbackend.txt").inputStream() val content = inputStream.bufferedReader().use < it.readText() >println(content) > 
  • first, we get an InputStream from File object,
  • next, using inputStream.bufferedReader() we get a BufferedReader responsible for reading streams,
  • finally, to read the content we use the use < it.readTest() >command which is the same as Closeable.use(Reader.readText()) in Java,
  • note that the last operation will automatically close the InputStream .
Tutorials: - one - two - three 

3.2. Read line by line

In the following example we make use of Reader.useLines(. ) method to read a file line by line:

import java.io.File import java.io.InputStream fun main(args: Array) < val inputStream: InputStream = File("frontbackend.txt").inputStream() val out = mutableListOf() inputStream.bufferedReader().useLines < lines ->lines.forEach < out.add(it) >> out.forEach < println(it) >> 
  • first, we read an InputStream of a frontbackend.txt file,
  • next, we created a mutable list that will hold file content lines,
  • then, we read all lines and put them in our collection using the bufferedReader().useLines method,
  • the final step is to print all lines from our collection.

If everything is correct you should get the same result as in the first approach:

Tutorials: - one - two - three 

4. Conclusion

In this short article, we presented ways to read a file in Kotlin. The first method read all file content at once, second read line by line.

Источник

Read From Files using InputReader in Kotlin

Basically, kotlin.io provides a nice, clean API for reading from and writing to files. In this article, we are going to discuss how to read from files using inputReader in Kotlin. One way of doing this is by using inputreader. We will see how to do that in this article.

Example

There are a lot of ways to go about reading from a file, but it is very important to understand the motivation behind them so as to be able to use the correct one for our purpose. First, we will try to get the Input Stream of the file and use the reader to read the contents:

Kotlin

In the preceding code block, gfg.txt is simply a file that we want to read. The file is located in the same folder as our code source file. If we need to read a file located in a different folder, it looks similar to the following:

This piece of code simply takes all the text in the file and prints it on the console. Another way of reading file contents is by directly creating a reader of the file as we do in this code:

Kotlin

The output of both preceding code blocks will simply be the text in the file as it is. In our case, it was as follows:

GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. The content on GeeksforGeeks has been divided into various categories to make it easily accessible for the users. Whether you want to learn algorithms, data structures or it is the programming language on it's own which interests you. GeeksforGeeks has covered everything. Even if you are looking for Interview preparation material. GeeksforGeeks has a vast set of company-wise interview experiences to learn from. that gives a user insights into the recruitment procedure of a company. Adding to this, it serves as a perfect platform for users to share their knowledge via contribute option.

Now, what if we want to read the file line by line because we want to do some processing on each line? In that case, we use the useLines( ) method in place of use(). Check out the following example, where we get an input stream from the file and use the useLines () method to get each line one after the other:

Kotlin

Alternatively, if we wish to use a reader directly on the file, we do this:

Kotlin

The output, in this case, will be the following:

$ GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. $ The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. $ The content on GeeksforGeeks has been divided into various categories to make it easily accessible for the users. $ Whether you want to learn algorithms, data structures or it is the programming language on it's own which interests you. $ GeeksforGeeks has covered everything. $ Even if you are looking for Interview preparation material. $ GeeksforGeeks has a vast set of company-wise interview experiences to learn from. $ that gives a user insights into the recruitment procedure of a company. $ Adding to this, it serves as a perfect platform for users to share their knowledge via contribute option.

Did you note that we used the use() and useLines() methods for reading the file? The call to the Closeable. use () function will automatically close the input at the end of the lambda’s execution. Now, we can of course use Reader.readText (), but that does not close the stream after execution. There are other methods apart from use(), such as Reader.readText(), and so on, that can be used to read the contents of a stream or file. The decision to use any method is based on whether we want the stream to be closed on its own after execution, or we want to handle closing the resources, and whether or not we want to read from a stream or directly from the file.

BufferedReader reads a couple of characters at a time from the input stream and stores them in the buffer. That’s why it is called BufferedReader. On the other hand, Input Reader reads only one character from the input stream and the remaining characters still remain in the stream. There is no buffer in this case. This is why BufferedReader is fast, as it maintains a buffer, and retrieving data from the buffer is always quicker compared to retrieving data from disk.

Источник

Читайте также:  First android app java
Оцените статью