Tuesday, August 15, 2017

Kotlin: File reader and writer

Welcome to kotlin Series

Kotlin


In this post, we are going to learn about kotlin IO (input or output)

we basically learn about file reader and writer.
In this post, we are going to write a program that takes text from the console and save it on computer hard disk as a text file.
Let start-

First, we are going to create a method for saving file, method name writeToFile
Follow those step:
1. take a String parameter
 2. Create an instance of FileWriter
3. in try-catch block write this string by using write method.
See the code-
fun writeToFile(str: String) {

    val writer = FileWriter("text.txt", true)

    try {
        writer.write(str+"\n")

    } catch (ex: Exception) {
        println(ex.message)

    } finally {
        writer.close()
    }
}
Now time to create the Main method-
in the main method-
1. first we show a message to user to write some text
2. take those text and save in on a variable
3. after the call the writeToFile method and parameter is this variable.
see the code-
fun main(args: Array<String>) {
    println("Write a message")
    val str: String = readLine().toString()

    writeToFile(str)

}


Now time to read this text file and print the text in the console-
Follow those step-
1.create a method name readFile()
2. in try-catch block create an instance of FileReader class
3. print text to the console by using readText() method
see the code-
fun readFile(){

    try {
        val read = FileReader("text.txt")

        println(read.readText())


    } catch (e:Exception){
        println(e.message)
    }

}
In the main method, call this method-
fun main(args: Array<String>) {
    println("Write a message")
    val str: String = readLine().toString()

    writeToFile(str)

    readFile()

}

Now run this program-
after running the programming this will show you like below picture
input some text I input: Hello I am shudipto trafder

kotlin-io-code

Note: Green colored text is your input text and white color text is output text( that read from the file)
this is the text file that saved

kotlin-io-output

Thanks for reading this post.
Happy coding.

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :