Updated April 3, 2023
Introduction to Kotlin Write to File
Kotlin write to file is used to provide the extension function or may also use the existing other programming language code that writes for content to a file by using the writeText() method and most probably it will take the string as the datatype argument and it writes it into the file will create the new file if no file exists error and with specified name, if the file is in already exists will replace the file the data is first encoded using the UTF-8 charset format it’s a default and can also specify other charset.
Syntax of Kotlin Write to File
Kotlin language has many default keywords, variables, and other functions to execute and implement the kotlin in both mobile and web-based applications. It has some features like file creation with reading and writing operations on the application.
import java.io.File
fun main()
{
val variablename=""
val vars2=File(variablename)
vars2.writeText(values)
--some logic codes depending on the requirement----
}
The above codes are the basic syntax for utilizing the writeText() method in the file concept. We can create the file and write the datas to the file. We import the file package in the code so that we can utilize the file feature.
How Write to File in Kotlin?
The kotlin language write to file is the feature and it is used to write the datas in the file. It is the method writeText() that will take String datatype values as the parameters and write them into the file. If suppose the file is not created it will create the new file first and then it will write the datas to the file. If the file is there it will throw the file exists error and if not there means it throws no file that exists with the specified names.
If the file is in an already existing state it will replace the existing file datas. And also the given data is first encoded using the UTF-8 charset as the default one and it can also specify with any other charset. It is because the writeText() method will replace all the data contents which are present in the file it will prevent the present data from getting the data lost and such scenarios we can use another method like appendText() function for to instead of writing the datas in the writeText() function.
We used different types of java classes like PrintWriter, writeText(), bufferedWriter() and java.io.File.printWriter() and its method for performing the operations in the application every class wants to create a separate instance for calling the write operations in the kotlin application.
Examples of Kotlin Write to File
Given below are the examples of Kotlin Write to File:
Example #1
Code:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardOpenOption
class first (lst:MutableList<Any>){
var vars:MutableList<Any> = lst
fun exam():Boolean = vars.isEmpty()
fun exam1():Int = vars.count()
override fun toString() = vars.toString()
fun enqueue(element:Any){
vars.add(element)
}
fun dequeue():Any?{
if (this.exam()){
return null
} else {
return vars.removeAt(0)
}
}
fun peek():Any?{
return vars[0]
}
}
fun multopera(x: Int, y: Int): Int {
var num = x.times(y)
return num
}
fun Employee( empName: String , empdept: Char , empid: Int) {
println("Please enter the employee name : $empName")
println("Please enter the employee department: $empdept")
println("Please enter employee id: $empid")
}
fun main() {
val strinp = "F:/July/JulyTest.txt"
val a = File(strinp)
val b = "Welcome To My Domain its the first example that related to the kotlin write to file concept\n"
val empName = "Sivaraman\n"
val empid = 41
val empdept = 'I'
Employee(empName,empdept,empid)
Employee("Kumar",'I',43)
Files.write(a.toPath(), b.toByteArray(), StandardOpenOption.APPEND)
a.writeText(empName)
println("The data is write on the specific path file successfully")
var mult = multopera(3,5)
println("Thank you users the multiplication of two numbers is: $mult")
val s = 05.43f
val s1 = 41.32f
val out = s * s1
println("Thank you users for spenting the time with our application $out")
var temp = 0
var count = 5642381
while (count != 0) {
count /= 7
++temp
}
println("Your net output result is calculated: $temp")
var x1 = first(mutableListOf("Welcome To My Domain its the first example that related to the kotlin write to file concept",8,36,"Have a nice day users please try again"))
println(x1.enqueue(6))
println(x1)
println(x1.dequeue())
println(x1)
println(x1.peek())
println(x1)
println(x1.exam1())
println(x1.exam())
}
Output:
In the above example we used write() and writeText() method for to write the datas in the file.
Example #2
Code:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardOpenOption
class Test {
fun secondMethod(){
val m=7432
println(m)
var aLs=ArrayList<String>()
aLs.add("Welcome Users please entered your first input element")
aLs.add("Welcome Users please entered your second input element")
aLs.add("Welcome Users please entered your third input element")
aLs.add("Welcome Users please entered your fourth input element")
aLs.add("Welcome Users please entered your fifth input element")
}
}
fun secondMethod(vararg num: Int): Int
{
var a = 0
num.forEach {num -> a += num}
return a
}
fun main() {
val fN = "F:/July/SecondJuly.txt"
val finput = File(fN)
val inps = "Welcome To My Domain its the second example that related to the kotlin write to file concept"
finput.writeText(inps)
println("Thank you users for spenting the time your inputs are successfully write it on the file")
println("Your total sum is: ${secondMethod(5, 10, 15, 20)}")
var ls=ArrayList<String>()
L.add("This month is July month")
for(i in ls)
print("your inputs are iterated and $i ")
println()
ls.set(5,"Thank you users have a nice day your input months are validated and stored it on the arraylist")
for(j in ls)
print("Have a Nice day users please try again $j ")
val te=Test()
println(te.secondMethod())
}
Output:
In the second example, we used writeText() method for to write the datas in the file.
Example #3
Code:
import java.io.File
fun main() {
val fpath = "f:July/third.txt"
val floc = File(fpath)
floc.printWriter().use { wrt ->
wrt.println("Your first input")
wrt.println("Your second input")
}
floc.bufferedWriter().use { wrt ->
wrt.write("Your third input\n")
wrt.write("Your fourth input\n")
wrt.write("Your fifth input\n")
}
println("Your inputs are successfully written in the file")
}
Output:
In the final example, we used printWriter() and bufferedWriter() method for to write the datas in the file.
Conclusion
In the kotlin language, we used a lot of default classes and their methods to implement the application. Each and every method behaves in different behavior and its features like that file write is one of the features for to write the user input and output datas in the file using default methods.
Recommended Articles
This is a guide to Kotlin Write to File. Here we discuss the introduction, syntax, and working of write-to file in Kotlin along with different examples respectively. You may also have a look at the following articles to learn more –