Home »
Scala
How to write in a file in Scala?
By IncludeHelp Last updated : November 16, 2024
Scala - Write to a File
To write text to file in Scala, we have to use the java.io object as it relies on java object for performing some functions.
In scala, the PrintWriter and FileWriter are employed to perform the write to file operation.
Steps involved in writing to file
Here, are some steps that we will follow to write to a file in Scala,
- Create a new PrintWriter / FileWriter object using the fileName.
- Use the write() function to write to the file.
- Use close method after completing the write operation.
Syntax
Writing to a file using PrintWriter,
val printWriter_name = new PrintWriter(new File("fileName"))
printWriter_name.write("text")
printWriter_name.close
Syntax
Writing to a file using FileWriter,
val file = new File(fileName)
val writer_name = new BufferedWriter(new FileWriter(file))
writer_name.write(text)
writer_name.close()
Example 1
Writing to a file - "includehelp.txt" text - "scala is an amazing programming language." using PrintWriter.
import java.io._
object MyObject {
def main(args: Array[String]): Unit = {
val writer = new PrintWriter(new File("includehelp.txt"))
writer.write("Scala is an amazing programming language")
writer.close()
}
}
Output
//The program will write content to the file.
Explanation
In the above code, we have created the writer that will be used to write to file using the write() method.
Example 2
We will write to the file "text.txt", the text "I love programming Scala" using FileWriter.
import java.io._
object MyObject {
def main(args: Array[String]): Unit = {
val writeFile = new File("text.txt")
val inputString = "I love programming in Scala"
val writer = new BufferedWriter(new FileWriter(writeFile))
writer.write(inputString)
writer.close()
}
}
Output
// This will write the content of the inputString to the file named "text.txt".
Explanation
In the above code, we have used the FileWriter to write to the file name "text.txt", the contents to be written are given by inputString and the method write() is employed to perform the writing task.