Home » Scala language

File Handling in Scala

Scala file handling: File handling deals with all sorts of input and output in the file as per the requirement of the code. Scala also provides its programmer to hack into the file system. In this Scala file handling tutorial, we will learn about file handing in Scala.
Submitted by Shivang Yadav, on August 09, 2019

Scala file handling

File handling is storing, excessing and modifying data from in a file. In Scala, we can fetch data from a file, store data in a file in different ways. For this Scala, uses libraries from java, the library used by Scala in file handing is java.io.File.

Now, let's dig into step by step data handing that will clear all things related to file handling in Scala,

Creating a file in Scala and writing content to it

As Scala, uses Java library the libraries of java methods are used.

In this program to will create a new file called by file myfile.txt and then write one sentence in the file.

Program to create a file in Scala

import java.io._

object WriteFileExample { 
    def main(args:Array[String]){ 
        // creating file object
        val file = new File("myfile.txt" )  
        //creating object of the PrintWrite 
        //by passing the reference to the file
        val pw = new PrintWriter(file)  
        //writing text to the file
        pw.write("Welcome @ IncludeHelp\n")
        pw.write("writing text to the file\n")
        //closing the PrintWriter
        println("PrintWriter saved and closed...")


PrintWriter saved and closed...

Reading Content line by line in Scala

You can alternatively read the contents of a file in Scala line by line,

import scala.io.Source

object MainObject{
    def main(args:Array[String]){
        //file name
        val filename = "myfile.txt"  
        //file reading - creating object name by passing
        //filename i.e. file object
        val filereader = Source.fromFile(filename)  
        //printing characters


Welcome @ IncludeHelp
writing text to the file

Code explanation:

The program uses the scala.io.Source class to use the getLines method that returns a single line of the code.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.