Android kotlin inputstream to file

How to read File in Kotlin

In this tutorial, I will show you how to read File in Kotlin using InputStream or BufferedReader or File directly.

Create the file

First, we need a file to read. So create a file named bezkoder.txt with following content:

Because we don’t indicate path for bezkoder.txt file, so you should put it in the root folder of the Project (the folder src is located in).

If you wanna read file in resources folder \app\src\main\res\, just change the path:
File(«bezkoder.txt») -> File(«src/main/res/bezkoder.txt»)

Kotlin read File using InputStream

Read all lines

  • retrieve InputStream from File, then get BufferedReader using bufferedReader() method
  • use Closeable.use() method along with Reader.readText() method inside block.

Note:
– Reader implements Closeable
– Closeable.use() will automatically close the input at the end of the lambda’s execution

Read line by line

  • retrieve InputStream from File, then get BufferedReader using bufferedReader() method
  • use Reader.useLines() method with Kotlin Sequence (a sequence of all the lines) inside block. It will automatically close the reader once the processing is complete

Kotlin read File using BufferedReader

Read all lines

  • create BufferedReader from File
  • use BufferedReader.use() method along with Reader.readText() method inside block.

Read line by line

  • create BufferedReader from File
  • use Reader.useLines() method that will automatically close the reader once the processing is complete

Kotlin read File directly

There are two ways to read all lines of a file using File directly:

  • File.useLines() method along with Kotlin Sequence
  • File.readLines() method to return a List

Conclusion

Today we’ve learned many ways to use Kotlin to read a File line-by-line or all lines. Now you can use InputStream or BufferedReader or File directly to do the work.

Happy Learning! See you again.

Further Reading

3 thoughts to “How to read File in Kotlin”

Thank you for writing this Kotlin tutorial that shows many ways to read a File.

Hi, thanks for this tutorial. You show me many ways to read a File using Kotlin.

Источник

Kotlin Read File

Kotlin Read File – 6 Different Ways

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

  1. Prepare file object with the location of the file passed as argument to File class constructor.
  2. File.bufferedReader returns a new BufferedReader for reading the content of the file.
  3. Use BufferedReader.readLines() to read the content of the file.
Читайте также:  Adv manager unable to locate adb android studio

Kotlin Program – example.kt

Output

Content of file is printed to the console.

File.forEachLine() : Read a file line by line in Kotlin

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.forEachLine function and read each line of the file.

Kotlin Program – example.kt

Output

Content of file is printed to the console.

File.inputStream() : Read contents of file to InputStream

  1. Prepare file object with the location of the file passed as argument to File class constructor.
  2. File.inputStream() returns a new InputStream for the file.
  3. 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

Content of file is printed to the console.

File.readBytes() : returns entire content of file as a ByteArray

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readBytes() function to get ByteArray. This byte array contains all the file contents.
  3. Use for loop to iterate over the byte array and access the contents of file byte by byte.

Kotlin Program – example.kt

Content of file is printed to the console.

File.readLines() : returns entire content of file as a List of lines

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readLines() function to get all the lines in the text file as List of Strings.
  3. You can access the list using for loop to read each line of the file.

Kotlin Program – example.kt

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.

  1. Prepare file object with the location passed as argument to File constructor.
  2. Use File.readText() function that returns entire content of file as a String.

Kotlin Program – example.kt

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.

Источник

Как в Kotlin прочитать все содержимое InputStream в строку?

Недавно я видел код для чтения всего содержимого InputStream строки в Kotlin, например:

И даже это выглядит более плавным, поскольку автоматически закрывает InputStream :

Или небольшое изменение этого:

Затем эта функциональная складчатая штуковина:

Или плохой вариант, который не закрывает InputStream :

Но все они неуклюжие, и я постоянно нахожу новые и разные версии одного и того же . а некоторые из них даже не закрывают InputStream . Какой неуклюжий (идиоматический) способ читать InputStream ?

Примечание: этот вопрос намеренно написан и на него дан ответ автора ( вопросы с ответами), так что идиоматические ответы на часто задаваемые темы Kotlin присутствуют в SO.

В Kotlin есть специальные расширения только для этой цели.

Простейший:

И в этом примере вы можете выбрать между bufferedReader() или просто reader() . Вызов функции Closeable.use() автоматически закроет ввод в конце выполнения лямбды.

Дальнейшее чтение:

Если вы часто занимаетесь подобными вещами, вы можете написать это как функцию расширения:

Который затем можно было бы легко назвать как:

С другой стороны, все функции расширения Kotlin, для которых требуется знать charset значение по умолчанию UTF-8 , поэтому, если вам требуется другая кодировка, вам необходимо настроить приведенный выше код в вызовах, чтобы включить кодировку для reader(charset) или bufferedReader(charset) .

Предупреждение: вы можете увидеть примеры короче:

Источник

Kotlin read file tutorial

last modified July 5, 2020

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.

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.

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.

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

A mutable list is created.

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

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.

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.

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

An InputStream is created from a File with inputStream() .

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.

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.

Источник

Working with byte streams in Kotlin

Sometimes it is necessary to process data that is so large that it is no longer practical to load it all into memory. This is often the case in mobile apps, where computational resources are very limited, so it’s better to stream the data and avoid an OutOfMemoryException . Recently I was working in an app written in Kotlin that processes big files, up to 300 MB, so I decided to write down some useful tips for working with byte streams in Kotlin.

Extension functions

The Kotlin standard library has lots of extension functions that improve existing Java APIs. Most of them are really easy to implement, but nevertheless it’s great to have them at your disposal, plus, they often make code more readable. Here are some of my favorite extensions for byte streams:

  • File.inputStream() Convenient function for opening an InputStream to a file.
  • File.outputStream() Convenient function for opening an OutputStream to a file.
  • InputStream.reader() Creates a Reader from an InputStream . Useful for parsing text files. File also has a similar function, in case you don’t need the InputStream .
  • Closeable.use() . This makes sure that the stream is closed after you are done using it. This is great for avoiding leaking resources.
  • InputStream.copyTo() . This copies the contents of an InputStream to a OutputStream . This is super useful for copying or downloading files.

As an example of the usage of some of these functions here’s how you could implement a function for copying files:

This looks nice, but there’s no need to add this to your codebase because there is already and extension function for copying files, File.copyTo() , and it does exactly this but contains additional validations and configurable options.

The standard library is great, but it can only contain so many functions. As it is included as a regular dependency in Android projects, new problems could arise if it becomes too bloated. There are some things that you will have to implement yourself or look elsewhere. The next section is an example of this.

Tracking the number of processed bytes

Neither Java nor Kotlin have a built-in solution for tracking the number of processed bytes in a stream so that the UI can display the progress of the task. This is important because if you are processing large amounts of data, it will take a proportionally long amount of time. The user should be able to see the progress of the task and estimate how much time is left to complete it.

Читайте также:  Андроид диктофон по блютузу

The solution is to create wrapper classes that monitor the invocations of the read() and write() methods, tracking the number of processed bytes and calling a lambda function whenever this number increases. Here’s how I implemented it:

EDIT 2021-01-14: A minor bug in ObservableInputStream has been fixed.

EDIT 2021-01-25: It has been brought to my attention that not all InputStream methods were originally implemented in this snippet and this could cause problems. Methods available() , mark() , markSupported() , skip() , and reset() have now been added. Also, Java 9 introduces new InputStream methods readNBytes() and readAllBytes() . If you target Java 9 or later then you should override these methods as well to update the read bytes counter appropriately, otherwise you may end up with mysterious bugs.

To use this, wrap the original stream with one of these classes, attaching a lambda function to execute every time the number of processed bytes increases. For example here’s how you could report progress while downloading a file via HTTP:

Once again I use the convenient InputStream.copyTo() function to move bytes from the ObservableInputStream into the OutputStream that writes the file to internal storage. But, what if you wanted to do the opposite? There is no OutputStream.copyTo() , so how could you transfer data from OutputStream to InputStream ?

Transferring data from OutputStream to InputStream

This might sound a little odd, but there are legitimate cases for doing this. Just google “Java OutputStream to InputStream” and you’ll get thousands of results. Besides, it’s a good use case for one of Kotlin’s most recent features. Ideally you should always read from InputStream and then write into OutputStream , but imagine a scenario in which you know that some external library is about to write data to an OutputStream but you’d like to read that output, apply some transformation and then write it to a new stream.

At first glance this seems impossible because OutputStream doesn’t have a read() method, only write() . Java’s byte streams aren’t as easy to compose as UNIX streams in which you can just use the | operator to redirect the output of one program to the input of another. What you would have to do here is write to a “mocked” OutputStream that doesn’t really write data anywhere, just holds on to it until you request it. There is a Java class for this, PipedOutputStream , but there’s still one little problem.

PipedOutputStream lets you create a PipedInputStream so that you can read() the data that is being written, but none of this changes the fact that write() blocks the calling thread. This means that if you want to read the data as it is being written, you need to do it concurrently. The good news is that Kotlin has coroutines now, so you can easily offload the writing to new coroutine, and read on the current one.

Finally, here is a little example to illustrate how to use PipedOutputStream . Suppose you want to download a file via FTP, but you want to decompress it before it gets written to the internal storage. The solution is to download in one coroutine and decompress in the other one.

Coroutines make dealing with concurrency much easier. In fact, I was very surprised to see this code work correctly on my first try. Since I process multiple large files in parallel I make extensive use of Coroutines. I think this is my favorite feature and the biggest reason to switch to Kotlin for Android development.

Источник

Оцените статью