Introduction to Scala – Files I/O | File Handling in Scala

If You are interested to learn about the Scala Traits

Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files.

The following is an example program to writing to a file.

Example

import java.io._

object Demo {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("Hello Scala")
      writer.close()
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file.

Output

Hello Scala

Reading a Line from Command Line

Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line.

Example

object Demo {
   def main(args: Array[String]) {
      print("Please enter your input : " )
      val line = Console.readLine
      
      println("Thanks, you just typed: " + line)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Please enter your input : Scala is great
Thanks, you just typed: Scala is great

Reading File Content

Reading from files is really simple. You can use Scala’s Source class and its companion object to read files. Following is the example which shows you how to read from “Demo.txt” file which we created earlier.

Example

import scala.io.Source

object Demo {
   def main(args: Array[String]) {
      println("Following is the content read:" )

      Source.fromFile("Demo.txt" ).foreach { 
         print 
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Following is the content read:
Hello Scala

File Handling in Scala

File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter.

Creating a new file :

  1. java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
  2. File(String pathname) converts theparameter string to abstract path name, creating a new file instance.

Writing to the file

  1. java.io.PrintWriter includes all the printing methods included in PrintStream.

Below is the implementation for creating a new file and writing into it.

// File handling program
import java.io.File
import java.io.PrintWriter
  
// Creating object
object Geeks
{
    // Main method
    def main(args:Array[String])
    {
        // Creating a file 
        val file_Object = new File("abc.txt" ) 
   
        // Passing reference of file to the printwriter     
        val print_Writer = new PrintWriter(file_Object) 
  
        // Writing to the file       
        print_Writer.write("Hello, This is Geeks For Geeks") 
  
        // Closing printwriter    
        print_Writer.close()       
}
}     


A text file abc.txt is created and contains the string “Hello, This is Geeks For Geeks”

Scala does not provide class to write a file but it provide a class to read the files. This is the class Source. We use its companion object to read files. To read the contents of this file, we call the fromFile() method of class Source for reading the contents of the file which includes filename as argument.

Reading a File
scala.io.Source includes methods for iterable representation of the source file.
Source.fromFile creates a source from the input file.
file.next return the next element in the iteration and moves the iterator one step ahead.
file.hasnext checks if there is next element available to iterate.
getLines– Iterate through file line by line

Below is the implementation for Reading each character from a file.

// Scala File handling program
import scala.io.Source
  
// Creating object 
object GeeksScala
{
    // Main method
    def main(args : Array[String])
    {
        // file name
        val fname = "abc.txt" 
  
        // creates iterable representation 
        // of the source file            
        val fSource = Source.fromFile(fname) 
        while (fSource.hasNext)
        {
            println(fSource.next)
        }
  
        // closing file
        fSource.close() 
    }
}

Output:

We can use getLines() method to read individual lines instead of the whole file at once.
Below is the implementation for Reading each line from a file.

// Scala file handling program to Read each
// line from a single file
import scala.io.Source 
  
// Creating object
object gfgScala
{ 
    // Main method
    def main(args:Array[String])
    { 
        val fname = "abc.txt"
        val fSource = Source.fromFile(fname) 
        for(line<-fSource.getLines)
        { 
            println(line) 
        } 
        fSource.close() 
    } 
} 

Output:

Introduction to Scala – Files I/O | File Handling in Scala
Show Buttons
Hide Buttons