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 related topics,

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

1. Read a file 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. Read a file 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. Read a 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()
}
}
}
}

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete