How to write in a file in Scala?

Scala | Writing in files: Here, we are going to learn how to write to file in Scala with examples and working codes?
Submitted by Shivang Yadav, on May 20, 2020

Scala: Write text files

To write text to file in Scala, we have to use the 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,

  1. Create a new PrintWriter / FileWriter object using the fileName.
  2. Use the write() function to write to the file.
  3. Use close method after completing the write operation.


Writing to a file using PrintWriter,

    val printWriter_name = new PrintWriter(new File("fileName"))

Writing to a file using FileWriter,

    val file = new File(fileName)
    val writer_name = new BufferedWriter(new FileWriter(file))

Example 1:

Writing to a file - "includehelp.txt" text - "scala is an amazing programming language." using PrintWriter.


object MyObject {
    def main(args: Array[String]) {
        val writer = new PrintWriter(new File("includehelp.txt"))
        writer.write("Scala is an amazing programming language")


//The program will write content to the file. 


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.


object MyObject {
    def main(args: Array[String]) {
        val writeFile = new File("text.txt")
        val inputString = "I love programming in Scala"
        val writer = new BufferedWriter(new FileWriter(writeFile))


// This will write the content of the inputString to the file named "text.txt".


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.

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.