Ensuring stream closing with the use function
Whenever we are accessing the contents of a File
via FileInputStream
or FileOutputStream
, we should remember to close them once we've finished working on the file. Unclosed streams may lead to memory leaks and a significant decrease in performance. In this recipe, we are going to explore how to employ the use()
extension function offered by the standard library under the kotlin.io
package for automatic stream closing.
Getting ready
Make sure you have a sample non-empty file included in your project to read its contents. You can clone the sample project provided with the book's GitHub repository: https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook. In this recipe, we are going to use the file1.txt
file located in the src/main/resources
directory in the sample project.
How to do it...
- Import the
File.separator
constant and assign an alias to it:
import java.io.File.separator as SEPARATOR
- Declare a
String
storing a path to the file we...