Kotlin Reader Example

The java.io.Reader class provides a low-level API for reading character streams.

import java.io.FileReader

fun main(args : Array<String>){
    if (args.isEmpty()){
        println("Please provide a list of files separated by spaces")

    //Read each supplied file
    args.forEach { fileName ->

        //Open the file. The use() extension function sees to the details
        //of closing the file when finished
        FileReader(fileName).use {

            //Read a single character
            var character = it.read()

            //read() returns -1 at End of File
            while (character != -1){

                //Print the character (make sure to convert it to a Character)

                //Read the next character
                character = it.read()

The example program requires names of text files passed in as command line arguments so our first task is to check if we have any command line arguments. On line 4, we use the isEmpty() function on the args array object to check for an empty array. If true, we print a message to the user (line 5) and then exit the program (line 6).

Provided the program is still running, we begin by printing the contents of each file to the console. On line 10, we enter into a forEach statement to process each of the file supplied at the command line. Rather than using the standard it varaible name, we use fileName to help make the code more clear.

Line 14 performs the operation of actually opening the file. We do this by creating a new FileReader object and pass the name of the file into its constructor. Then we chain the object to the use() extension function. The use() function sees to the details of actually closing the file when we are finished with it, even in the case of an exception.

The file reader object is now referred to by the variable it. On line 17, we call it.read() to read a single character from the file and store it into the character variable. We then enter into a while loop that terminates when character is -1. The -1 value indicates we have reached the end of the file. Inside of the while loop, we print the character (line 23). Sicne read() returns an int, we have to call toChar() to print the actual character. Then on line 26, we update character to the next character in the stream.

Here is how I ran the program for those readers who wish to try it out.

kotlinc ReaderExample.kt -include-runtime -d readerExample.jar
java -jar readerExample.jar ReaderExample.kt

This invocation printed the example program to my console, but it works with any text file.

%d bloggers like this: