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

  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.

Syntax:

Writing to a file using PrintWriter,

    val printWriter_name = new PrintWriter(new File("fileName"))
    printWriter_name.write("text")
    printWriter_name.close

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]) {
        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]) {
        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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.