- Read a file in Kotlin
- 1. Using BufferedReader.lines() function
- 2. Using Files.lines() function
- 3. Using Files.readAllLines() function
- 4. Using Files.readAllBytes() function
- 5. Using Files.readString() function
- Kotlin Read File
- Example programs to read contents of a file in Kotlin
- File.bufferedReader() : How to read contents of a file into BufferedReader
- File.forEachLine() : Read a file line by line in Kotlin
- File.inputStream() : Read contents of file to InputStream
- File.readBytes() : returns entire content of file as a ByteArray
- File.readLines() : returns entire content of file as a List of lines
- File.readText() : returns entire content of file as a single string
- Conclusion
- Related Tutorials
- Kotlin read file bytes
- copyRecursively
- copyTo
- deleteRecursively
- endsWith
- extension
- forEachBlock
- forEachLine
- inputStream
- invariantSeparatorsPath
- isRooted
- nameWithoutExtension
- normalize
- outputStream
- printWriter
- readBytes
- reader
- readLines
- readText
- relativeTo
- relativeToOrNull
- relativeToOrSelf
- resolve
Read a file in Kotlin
This article covers different ways to read the contents of a file in Kotlin.
1. Using BufferedReader.lines() function
In Kotlin, you can use the BufferedReader.lines() function to get a Stream of lines of text read from BufferedReader .
2. Using Files.lines() function
Alternatively, you can use the Files.lines() function to read all lines from a file using the specified charset.
3. Using Files.readAllLines() function
Another plausible way to read all lines from a file using the specified charset is to use the Files.readAllLines() function.
4. Using Files.readAllBytes() function
Another alternative is to use the readAllBytes() function, which returns a byte array having the bytes read from the specified file. To get a string out of file contents, you can pass the byte array to the String constructor.
5. Using Files.readString() function
Finally, you can also use the Files.readString() function to read all characters from a file into a string using the specified charset.
That’s all about reading a file in Kotlin.
Average rating 5 /5. Vote count: 2
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂
This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it
Kotlin Read File
Kotlin Read File – We can read the contents of a file in Kotlin either by using standard methods of the java.io.File class, or the methods that Kotlin provides as an extension to java.io.File.
We shall look into example programs for the extension methods, provided by Kotlin to Java‘s java.io.File Class, to read the contents of a file.
Example programs to read contents of a file in Kotlin
- File.bufferedReader() : To read contents of a file into BufferedReader
- File.forEachLine() : To read a file line by line in Kotlin
- File.inputStream() : To read contents of file to InputStream
- File.readBytes() : To read contents of file to ByteArray
- File.readLines() : To read lines in file to List of String
- File.readText() : To read contents of file to a single String
File.bufferedReader() : How to read contents of a file into BufferedReader
- Prepare file object with the location of the file passed as argument to File class constructor.
- File.bufferedReader returns a new BufferedReader for reading the content of the file.
- Use BufferedReader.readLines() to read the content of the file.
Kotlin Program – example.kt
import java.io.File /** * Created by www.tutorialkart.com * Example program to read contents of a file in Kotlin into BufferedReader */ fun main(args: Array) < val file = File("input"+File.separator+"contents.txt") val bufferedReader = file.bufferedReader() val text:List= bufferedReader.readLines() for(line in text) < println(line) >>
Good Day ! Welcome to Kotlin Tutorials in www.tutorialkart.com. Learn Kotlin easily here. Happy learning. Process finished with exit code 0
Content of file is printed to the console.
File.forEachLine() : Read a file line by line in Kotlin
- Prepare file object with the location passed as argument to File constructor.
- Use File.forEachLine function and read each line of the file.
Kotlin Program – example.kt
import java.io.File /** * Created by www.tutorialkart.com * Example program to read contents of a file in Kotlin line by line */ fun main(args: Array) < val file = File("input"+File.separator+"contents.txt") file.forEachLine < println(it) >>
Good Day ! Welcome to Kotlin Tutorials in www.tutorialkart.com. Learn Kotlin easily here. Happy learning Kotlin. Process finished with exit code 0
Content of file is printed to the console.
File.inputStream() : Read contents of file to InputStream
- Prepare file object with the location of the file passed as argument to File class constructor.
- File.inputStream() returns a new InputStream for the file.
- Then you can read bytes from the stream and convert it to a String. This string is content of the file.
Read Content of File to InputStream and then to a String
Kotlin Program – example.kt
import java.io.File import java.io.InputStream /** * Created by www.tutorialkart.com * Example program to read contents of a file in Kotlin to InputStream */ fun main(args: Array) < val file = File("input"+File.separator+"contents.txt") var ins:InputStream = file.inputStream() // read contents of IntputStream to String var content = ins.readBytes().toString(Charset.defaultCharset()) println(content) >
Content of file is printed to the console.
File.readBytes() : returns entire content of file as a ByteArray
- Prepare file object with the location passed as argument to File constructor.
- Use File.readBytes() function to get ByteArray. This byte array contains all the file contents.
- Use for loop to iterate over the byte array and access the contents of file byte by byte.
Kotlin Program – example.kt
import java.io.File /** * Created by www.tutorialkart.com */ fun main(args: Array) < val file = File("input"+File.separator+"contents.txt") var bytes:ByteArray = file.readBytes() for(byte in bytes)< print(byte.toChar()) >>
Content of file is printed to the console.
File.readLines() : returns entire content of file as a List of lines
- Prepare file object with the location passed as argument to File constructor.
- Use File.readLines() function to get all the lines in the text file as List of Strings.
- You can access the list using for loop to read each line of the file.
Kotlin Program – example.kt
import java.io.File /** * Created by www.tutorialkart.com */ fun main(args: Array) < val file = File("input"+File.separator+"contents.txt") var lines:List= file.readLines() for(line in lines) < println(line) >>
Content of file is printed to the console.
File.readText() : returns entire content of file as a single string
You can also read whole content of the file as a single string. Follow these steps.
- Prepare file object with the location passed as argument to File constructor.
- Use File.readText() function that returns entire content of file as a String.
Kotlin Program – example.kt
import java.io.File /** * Created by www.tutorialkart.com */ fun main(args: Array)
Content of file is printed to the console.
Conclusion
In this Kotlin Tutorial – Kotlin Read File, we have learned to read the contents of a file in Kotlin, read a file to a byte array, read a file to InputStream, read a file to list of strings, read a file line by line, read a file to BufferedReader.
Related Tutorials
Kotlin read file bytes
Returns a new BufferedWriter for writing the content of this file.
fun File . bufferedWriter (
charset : Charset = Charsets.UTF_8 ,
bufferSize : Int = DEFAULT_BUFFER_SIZE
) : BufferedWriter
copyRecursively
Copies this file with all its children to the specified destination target path. If some directories on the way to the destination are missing, then they will be created.
fun File . copyRecursively (
target : File ,
overwrite : Boolean = false ,
onError : ( File , IOException ) -> OnErrorAction = < _, exception ->throw exception >
) : Boolean
copyTo
Copies this file to the given target file.
fun File . copyTo (
target : File ,
overwrite : Boolean = false ,
bufferSize : Int = DEFAULT_BUFFER_SIZE
) : File
deleteRecursively
Delete this file with all its children. Note that if this operation fails then partial deletion may have taken place.
endsWith
Determines whether this file path ends with the path of other file.
Determines whether this file belongs to the same root as other and ends with all components of other in the same order. So if other has N components, last N components of this must be the same as in other. For relative other, this can belong to any root.
extension
Returns the extension of this file (not including the dot), or an empty string if it doesn’t have one.
forEachBlock
Reads file by byte blocks and calls action for each block read. Block has default size which is implementation-dependent. This functions passes the byte array and amount of bytes in the array to the action function.
Reads file by byte blocks and calls action for each block read. This functions passes the byte array and amount of bytes in the array to the action function.
fun File . forEachBlock (
blockSize : Int ,
action : ( buffer : ByteArray , bytesRead : Int ) -> Unit )
forEachLine
Reads this file line by line using the specified charset and calls action for each line. Default charset is UTF-8.
inputStream
Constructs a new FileInputStream of this file and returns it as a result.
invariantSeparatorsPath
Returns path of this File using the invariant separator ‘/’ to separate the names in the name sequence.
isRooted
Determines whether this file has a root or it represents a relative path.
nameWithoutExtension
Returns file’s name without an extension.
normalize
Removes all . and resolves all possible .. in this file name. For instance, File(«/foo/./bar/gav/../baaz»).normalize() is File(«/foo/bar/baaz») .
outputStream
Constructs a new FileOutputStream of this file and returns it as a result.
printWriter
Returns a new PrintWriter for writing the content of this file.
readBytes
Gets the entire content of this file as a byte array.
reader
Returns a new FileReader for reading the content of this file.
readLines
Reads the file content as a list of lines.
readText
Gets the entire content of this file as a String using UTF-8 or specified charset.
relativeTo
Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.
relativeToOrNull
Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.
relativeToOrSelf
Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.
resolve
Adds relative file to this, considering this as a directory. If relative has a root, relative is returned back. For instance, File(«/foo/bar»).resolve(File(«gav»)) is File(«/foo/bar/gav») . This function is complementary with relativeTo, so f.resolve(g.relativeTo(f)) == g should be always true except for different roots case.
Adds relative name to this, considering this as a directory. If relative has a root, relative is returned back. For instance, File(«/foo/bar»).resolve(«gav») is File(«/foo/bar/gav») .