Kotlin IO

File IO in Kotlin.

// Kotlin simply supplements the existing Java IO libraries with kotlin.io package
// Note text file in base directory of project <-
fun main() {
    File("testfile.txt").reader()
    // Abbreviates the Java declaration: new InputStreamReader(new FileInputStreamReader(new File("testfile.txt")), UTF-8")

    val lines = File("testfile.txt").reader().readLines() // DO NOT USE THIS FUNCTION FOR HUGE FILES. Reads entire file into memory.
    // Closes the Stream for us. Returns listOf<String>
    lines.forEach { println(it)}

    val reader2 = File("testfile.txt").reader()
    val lines2 = reader2.readText() // Returns one String which we would have to parse and close the Stream ourselves
    println("Lines2: $lines2") // Prints fine as text contains newlines
    reader2.close()
    println("======")

    val lines3 = File("testfile.txt").reader().use { it.readText() } // Closes the Reader itself - .use functions close the resource
    println("Lines3: $lines3")
    println("======")

    val lines4 = File("testfile.txt").bufferedReader().use { it.readText() } // BufferedReader
    println("Lines4: $lines4")
    println("======")

    val lines5 = File("testfile.txt").readText() // Version of readText which runs from the File class - limit of 2GB
    println("Lines5: $lines5")
    println("======")

    // If we don't want to read the whole file at once:
    File("testfile.txt").reader().forEachLine { println(it) } // Closes the resource for us
    println("======")

    // If we don't want to read the whole file at once:
    File("testfile.txt").reader().useLines { it.forEach { println(it) } } // useLines returns a reference so we need forEach. More verbose
    println("======")

    // Binary files - best done by using Java methods. No great enhancements in Kotlin.
    val di = DataInputStream(FileInputStream("testfile.bin"))
    var si: String

    try {
        while (true) {
            si = di.readUTF()
            println("Binary file: $si")
        }
    } catch (e: EOFException) {

    }

    // Writing files is no different to Java

    // Try with resources. To make sure a resource is released after using it use try...finally block, or better: try with resources. Kotlin method is to use one of the .use functions (see above)

}