50

There may be various way to read plain text file in kotlin.

I want know what are the possible ways and how I can use them.

7 Answers 7

86

1. Using BufferedReader

 import java.io.File import java.io.BufferedReader fun main(args: Array<String>) { val bufferedReader: BufferedReader = File("example.txt").bufferedReader() val inputString = bufferedReader.use { it.readText() } println(inputString) } 

2. Using InputStream

Read By Line

 import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputStream: InputStream = File("example.txt").inputStream() val lineList = mutableListOf<String>() inputStream.bufferedReader().forEachLine { lineList.add(it) } lineList.forEach{println("> " + it)} } 

Read All Lines

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

3. Use File directly

 import java.io.File import java.io.BufferedReader fun main(args: Array<String>) { val lineList = mutableListOf<String>() File("example.txt").useLines { lines -> lines.forEach { lineList.add(it) }} lineList.forEach { println("> " + it) } } 
Sign up to request clarification or add additional context in comments.

3 Comments

File.useLines() that's a new one to me. Let's see in which version of the jdk that appeared .. Oh that's a Kotlin add-on for Reader.
What are the differences between the options?
This one is the best answer for newer versions.
39

I think the simplest way to code is using kotlin.text and java.io.File

import java.io.File fun main(args: Array<String>) { val text = File("sample.txt").readText() println(text) } 

4 Comments

This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
@YaMiN - This limitation is so overblown. How often does anyone look up "how to read a text file" and they're omitting the fact that the file is over 2 GB? How many files does anyone have that are over 2 GB? My computer only has a 512 GB harddrive, so there's no way I have more than 256 files on my computer that I can't use this on, and I'd bet that if any exist (they probably don't), they aren't text files at all. I just checked. The largest file on my computer is iMovie.app (actually a dir) which is 2.65 GB. Next nine largest are also apps. Largest actual file is 500 MB, and it's HTML.
@ArtOfWarfare I just wanted to point out a fact. The reality or logistics of having or not having a 2 GB text file is another discussion.
Bear in mind that the amount of memory needed to store a string could be 2× or more its size on disk, because in general Strings are stored in UTF-16.  (It's not quite as simple as that, but the fact remains that you may need significantly more memory.)  And that you can easily end up making several copies in memory as soon as you try to process it at all.  And that you might have much less than 2GB of heap available.  And that you can't usually tell in advance what sort of files someone might try to run through your program.  Ultimately, processing line-by-line is good practice if you can.
9

Anisuzzaman's answer lists several possibilities.

The main differences between them are in whether the file is read into memory as a single String, read into memory and split into lines, or read line-by-line.

Obviously, reading the entire file into memory in one go can take a lot more memory, so that's something to avoid unless it's really necessary.  (Text files can get arbitrarily big!)  So processing line-by-line with BufferedReader.useLines() is often a good approach.

The remaining differences are mostly historical.  Very early versions of Java used InputStream &c which didn't properly distinguish between characters and bytes; Reader &c were added to correct that.  Java 8 added ways to read line-by-line more efficiently using streams (e.g. Files.lines()).  And more recently, Kotlin has added its own extension functions (e.g. BufferedReader.useLines()) which make it even simpler.

Comments

7

The answers above here are all based on Kotlin Java. Here is a Kotlin Native way to read text files:

val bufferLength = 64 * 1024 val buffer = allocArray<ByteVar>(bufferLength) for (i in 1..count) { val nextLine = fgets(buffer, bufferLength, file)?.toKString() if (nextLine == null || nextLine.isEmpty()) break val records = parseLine(nextLine, ',') val key = records[column] val current = keyValue[key] ?: 0 keyValue[key] = current + 1 } fun parseLine(line: String, separator: Char) : List<String> { val result = mutableListOf<String>() val builder = StringBuilder() var quotes = 0 for (ch in line) { when { ch == '\"' -> { quotes++ builder.append(ch) } (ch == '\n') || (ch == '\r') -> {} (ch == separator) && (quotes % 2 == 0) -> { result.add(builder.toString()) builder.setLength(0) } else -> builder.append(ch) } } return result } 

See: https://github.com/JetBrains/kotlin-native/blob/master/samples/csvparser/src/csvParserMain/kotlin/CsvParser.kt

3 Comments

which are the key file access criteria, and what is extra fluff to create strings and datastructures for the read data?
Link is invalid
This does not seem like idiomatic Kotlin at all.
3

To read a text file, it must first be created. In Android Studio, you would create the text file like this:

1) Select "Project" from the top of the vertical toolbar to open the project "tool window" 2) From the drop-down menu at the top of the "tool window", select "Android" 3) Right-click on "App" and select "New" then -> "Folder" (the one with the green Android icon beside it) then -> "Assets Folder" 4) Right-click on the "assets" folder after it appears in the "tool window" 5) Select "New" -> "File" 6) Name the file, and included the extension ".txt" if it is text file, or ".html" if it is for WebView 7) Edit the file or cut and paste text into it. The file will now display under the "Project" files in the "tool window" and you will be able to double-click it to edit it at any time.

TO ACCESS THIS FILE, use a prefix of "application.assets." followed by someFunction(fileName). For example (in Kotlin):

val fileName = "townNames.txt" val inputString = application.assets.open(fileName).bufferedReader().use { it.readText() } val townList: List<String> = inputString.split("\n") 

Comments

0

how to apply Documents path on that:

fun main(args: Array<String>) { val inputStream: InputStream = File("example.txt").inputStream() val inputString = inputStream.bufferedReader().use { it.readText() } println(inputString) } 

Comments

0
fun main() { val inputString = File("file.csv") .bufferedReader() .use { it.readText() } println(inputString) } 

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.