read-write-files-kotlin

Check File existence ?

In Kotlin, to check if the file already exists, use File.exists(), exists() returns a Boolean value. It returns true if the file exists and false if the file does not exist.


import java.io.File
fun main(args: Array) {
    val filename = "chercher tech.txt"
    var fileObject = File(filename)
    var fileExists = fileObject.exists()
    if(fileExists){
        print("$filename file does exist.")
    } else {
        print("$filename file does not exist.")
    }
}

Exceptions in kotlin

Kotlin Create File

In Kotlin, new file could be created using

  • File.createNewFile()
  • File.writeText(text :String)
  • Files.writeBytes()
We will learn about how to use these file writing methods in kotlin.

File.createNewFile()

File.createNewFile() creates a new file, if it does not exist already and returns Boolean value of true. If the file exist at the path provided, then createNewFile() functions returns false. The file created is empty and has zero bytes written to it.

createNewFile() is the way in which exiting file will not overridden. Remaining ways will overwrite the file if it exists.

In below example, we will try to create new file and then we try to override it.


import java.io.File
fun main(args: Array) {
    val fileName = "cherchertech.txt"
    var fileObject = File(fileName)
    // create a new file
    val isNewFileCreated :Boolean = fileObject.createNewFile()
    if(isNewFileCreated){
        println("$fileName is created successfully.")
    } else{
        println("$fileName already exists.")
    }
    // try creating a file that already exists
    val isFileCreated :Boolean = fileObject.createNewFile()
    if(isFileCreated){
        println("$fileName is created successfully.")
    } else{
        println("$fileName already exists.")
    }
}

writeText()

writeText() function creates a new file if it does not exist already and writes the text (string argument) to the file. If an empty string is provided, the file is created and nothing is written to it.

if file exists in the path already then file will be overridden, Sets the content of this file as text encoded using UTF-8 or charset specified by the user.


import java.io.File
fun main(args: Array) {
    val fileName = "chercher tech.txt"
    var fileObject = File(fileName)
    // create a new file
    fileObject.writeText("This is some text for file writing operations")
}

Properties inkotlin

writeBytes()

writeBytes() function creates a new file and writes array of bytes provided to the file created. If this file already exists, it becomes overwritten.

Read files in Kotlin

We can read contents of a file in Kotlin either by using standard methods of java.io.File class, or the methods that Kotlin provides as an extension to java.io.File.

chercher tech.txt file content


Chercher tech provides the tutorials for the future technologies,
We are writing an article one per day
Actually the author is not a developer, he is a tester
first author thought to write a tutorial only for selenium then
he thought for  protractor
python and then UI path now writing kotlin file operations

bufferedReader()

bufferedReader() to read contents of a file into BufferedReader


import java.io.File
fun main(args: Array) {
    val file = File("chercher tech.txt")
    val bufferedReader = file.bufferedReader()
    val text:List = bufferedReader.readLines()
    for(line in text){
        println(line)
    }
}

forEachLine()

forEachLine() reads this file line by line using the specified charset and calls action for each line. Default charset is UTF-8


import java.io.File
fun main(args: Array) {
    val file = File("chercher tech.txt")
    file.forEachLine { println(it) }
}

inputStream()

inputStream() Constructs a new FileInputStream of this file and returns it as a result.


import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
fun main(args: Array) {
    val file = File("chercher tech.txt")
    var ins:InputStream = file.inputStream()
    // read contents of IntputStream to String
    var content = ins.readBytes().toString(Charset.defaultCharset())
    println(content)
}

readBytes()

readBytes() Gets the entire content of this file as a byte array. This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size.


import java.io.File
fun main(args: Array) {
    val file = File("chercher tech.txt")
    var bytes:ByteArray = file.readBytes()
    for(byte in bytes){
        print(byte.toChar())
    }
}

readLines()

readLines() Reads the file content as a list of lines. Do not use this function for huge files.


import java.io.File
fun main(args: Array) {
    val file = File("chercher tech.txt")
    var lines:List = file.readLines()
    for(line in lines){
        println(line)
    }
}

readText()

readText() Gets the entire content of this file as a String using UTF-8 or charset specified by user


import java.io.File
fun main(args: Array) {
    val file = File("chercher tech.txt")
    var content:String = file.readText()
    println(content)
}

Write content to files

Creating a file is different from writing a file, we can write content to file while creating it but sometime we may want to write to a file which is already present in the file system.

We can write a using writeText() function present in th File class


import java.io.File
fun main(args: Array) {
    val filename = "chercher tech.txt"
    // content to be written to file
    var content:String = "dummy text to show writing to file in koltin chercher tech"
    
	File(filename).writeText(content)
}


import java.io.PrintWriter
fun main(args: Array) {
    val filename = "chercher tech.txt"
    // content to be written to file
    var content:String = "dummy text to show writing to file in koltin chercher tech"
    // using java class java.io.PrintWriter
    val writer = PrintWriter(filename)
    writer.append(content)
    writer.close()
}

printWriter() function calls the PrintWriter constructor internally


import java.io.File
fun main(args: Array) {
    val filename = "chercher tech.txt"
    // content to be written to file
    var content:String = "dummy text to show writing to file in koltin chercher tech"
    // write content to file
    File(filename).printWriter().use { param ->
        param.println(content)
    }
}

Read all values in Properties File

Append content to a file in kotlin


What is the difference between simply writing to a file vs appending data to a file?
In the case of writing to a file, a program can start writing from the start but in the case of appending text, you start writing from the end of the file.

You can append text into an existing file in Kotlin by opening a file using appendText() function in File class.

One of the common examples of appending text to file is logging


import java.io.File
fun main(args: Array) {
    val filename = "chercher tech.txt"
    // content to be written to file
    var content:String = "dummy text to show writing to file in kotlin chercher tech"
    // write content to file
    File(filename).writeText(content)
    File(filename).appendText("ppppppp")
}

Excel Files with apache poi

Copy a file into another in kotlin


import java.io.File
fun main(args: Array) {
    val filename = "chercher tech.txt"
    val newFilename = "kotlin.txt"
    File(filename).copyTo(File(newFilename));
}

Override if the file exists


File(filename).copyTo(File(newFilename), true);

Don't override if the file exists


File(filename).copyTo(File(newFilename), false);

Reading a CSV file with Column Index

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group