Scala File IO - Write File, Read File With Examples

Today we will look into Scala File IO operations. File operations mainly include reading data from files or writing data into files. Here we will look into Scala read file and Scala write file programs.

Scala File IO

Scala Read File

We can use scala.io.Source to read data from a file. For reading a file, we have created a test file with below content.

data.txt


JournalDev is a great platform for Java Developers.
JournalDev is online log of Pankaj Kumar.

Here is a simple program where we are using Scala Source class to read file data to a String and then split it using regular expression to a Map. Finally we are printing the count of JournalDev in the file content.

Wordcount.scala


import scala.io.Source
object Wordcount {
  def main(args:Array[String]) {
  println(Source.fromFile("data.txt")) // returns scala.io.BufferedSource non-empty iterator instance
  val s1 = Source.fromFile("data.txt").mkString; //returns the file data as String
  println(s1)
  //splitting String data with white space and calculating the number of occurrence of each word in the file
  val counts = s1.split("\s+").groupBy(x=>x).mapValues(x=>x.length)
  println(counts)
  println("Count of JournalDev word:"+counts("JournalDev"))
  }
}

Below image shows the execution of Scala read file program and output.

Scala File IO - Write File, Read File With Examples

Word count line by line: Sometimes there arises a need to process each line rather than the whole contents of the file. This can be achieved through the getLines method. For example below code;


println(Source.fromFile("data.txt").getLines())
Source.fromFile("data.txt").getLines.foreach { x => println(x) };

will produce following output;


non-empty iterator
JournalDev is a great platform for Java Developers.
JournalDev is online log of Pankaj Kumar.

Now let us see how to extract specific set of lines.


Source.fromFile("data.txt").getLines.take(1).foreach { x => println(x) };
Source.fromFile("data.txt").getLines.slice(0, 1).foreach { x => println(x) };

take(n) method is used to Select first n values of the iterator where slice(from, until) returns part of the iterator where “from” index is the part of slice and “until” index is not. So both the lines in above code snippet are doing the same thing.

Scala Write to File

Scala standard library doesn’t contain any classes to write files, so we will use Java IO classes for scala write to file. Below is a simple program showing how to write files in scala.

Write.scala


import java.io.File
import java.io.PrintWriter
import scala.io.Source
object Write {
  def main(args: Array[String]) {
    val writer = new PrintWriter(new File("Write.txt"))
    writer.write("Hello Developer, Welcome to Scala Programming.")
    writer.close()
    Source.fromFile("Write.txt").foreach { x => print(x) }
  }
}

This will produce a file Write.txt with given content and then Source will read and print the same file data.

That’s all for Scala File IO example. You can see how simple it is to read file in Scala and write file in Scala using Java IO classes.

By admin

Leave a Reply

%d bloggers like this: