Reading and Writing Files in Kotlin - Different ways

There are multiple ways of reading and writing a text file, this is required while dealing with many applications.
 
  
More Kotlin topics,

Here are some of the many ways of reading files in Kotlin: 

1. Kotlin Program to illustrate reading from FileReader using BufferedReader

import kotlin.Throws
import kotlin.jvm.JvmStatic
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.lang.Exception

object ReadFile {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
// We need to provide file path as the parameter:
val file = File("/home/user/Desktop/sample.txt")
val br = BufferedReader(FileReader(file))
var st: String?
while (br.readLine().also { st = it } != null) println(st)
}
}

2. Kotlin Program to illustrate reading from FileReader using FileReader

import java.io.FileReader

object ReadingFromFile {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
// pass the path to the file as a parameter
val fr = FileReader("/home/user/Desktop/sample.txt")
var i: Int
while (fr.read().also { i = it } != -1) print(i.toChar())
}
}

3.Kotlin Program to illustrate reading from Text File using Scanner Class

import java.io.File
import java.util.*

object ReadFromFileUsingScanner {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
// pass the path to the file as a parameter
val file = File("/home/user/Desktop/sample.txt")
val sc = Scanner(file)
while (sc.hasNextLine()) println(sc.nextLine())
}
}
 

4.Using Stream- Read file line by line

import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths

object TestReadFile {
@JvmStatic
fun main(args: Array<String>) {
try {
Files.lines(Paths.get("/home/user/Desktop/sample.txt")).use { stream ->
stream.forEach { x: String? ->
println(
x
)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}


Here are some of the many ways of writing files in Kotlin: 

1. Write a file using FileWriter

import java.io.*
object WriteFile {
/**
* This class shows how to write file in Kotlin
* @param args
* @throws IOException
*/
@JvmStatic
fun main(args: Array<String>) {
val data = "I am writing this String to File in Kotlin"
writeUsingFileWriter(data)
println("Done")
}
/**
* Use FileWriter when number of write operations are less
* @param data
*/
private fun writeUsingFileWriter(data: String) {
val file = File("/home/user/Desktop/sample.txt")
var fr: FileWriter? = null
try {
fr = FileWriter(file)
fr.write(data)
} catch (e: IOException) {
e.printStackTrace()
} finally {
//close resources
try {
fr!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
 

2.Write a file using BufferedWriter

import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException

object WriteFile {
/**
* This class shows how to write file in Kotlin
* @param args
* @throws IOException
*/
@JvmStatic
fun main(args: Array<String>) {
val data = "I am writing this String to File in Kotlin"
writeUsingBufferedWriter(data,3)
println("Done")
}

/**
* Use BufferedWriter when number of write operations are more
* It uses internal buffer to reduce real IO operations and saves time
* @param data
* @param noOfLines
*/
private fun writeUsingBufferedWriter(data: String, noOfLines: Int) {
val file = File("/home/user/Desktop/sample.txt")
var fr: FileWriter? = null
var br: BufferedWriter? = null
val dataWithNewLine = data + System.getProperty("line.separator")
try {
fr = FileWriter(file)
br = BufferedWriter(fr)
for (i in noOfLines downTo 1) {
br.write(dataWithNewLine)
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
br!!.close()
fr!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
 

3.Write a file using FileOutputStream

import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


object WriteFile {
/**
* This class shows how to write file in Kotlin
* @param args
* @throws IOException
*/
@JvmStatic
fun main(args: Array<String>) {
val data = "I am writing this String to File in Kotlin"
writeUsingOutputStream(data)
println("Done")
}

/**
* Use Streams when you are dealing with raw data
* @param data
*/
private fun writeUsingOutputStream(data: String) {
var os: OutputStream? = null
try {
os = FileOutputStream(File("/home/user/Desktop/sample.txt"))
os.write(data.toByteArray(), 0, data.length)
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
os!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}


More Kotlin topics,
 
 
 

Popular posts from this blog

Spring boot video streaming example-HTML5

DataTable-Pagination example with Spring boot, jQuery and ajax

10 Best Job Posting Sites 2021-2022

Spring boot web project free download:User Registration System

Spring Boot + JPA/Hibernate One to Many mapping example

5 Hardest Puzzle,100% fail answers

Java security AES,SHA256,SHA512,MD5-Spring Boot Project Free Download

Spring Boot-AngularJS-Bootstrap-JPA-CRUD

ReactJS - Bootstrap - Buttons

Spring Boot file upload/download example