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.

Kotlin read a file with InputStream

The example creates an InputStream from a File and reads bytes from it. The bytes are transformed into text.
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset

fun main(args: Array<String>) {

    val fileName = "src/resources/sample.txt"
    val myFile = File(fileName)

    var ins: InputStream = myFile.inputStream()
    
    var content = ins.readBytes().toString(Charset.defaultCharset())
    println(content)
}
An InputStream is created from a File with inputStream():
var ins: InputStream = myFile.inputStream()
We read bytes from the InputStream with readBytes() and transform the bytes into text with toString():
var content = ins.readBytes().toString(Charset.defaultCharset())


Comments