- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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<String>) { 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 "<<Your workspace>>" && 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<String>) { 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 "<<Your workspace>>" && 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
Advertisements