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 to read data from a file. For reading a file, we have created a test file with below content.


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.


object Wordcount {
  def main(args:Array[String]) {
  println(Source.fromFile("data.txt")) // returns non-empty iterator instance
  val s1 = Source.fromFile("data.txt").mkString; //returns the file data as String
  //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("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;

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.


object Write {
  def main(args: Array[String]) {
    val writer = new PrintWriter(new File("Write.txt"))
    writer.write("Hello Developer, Welcome to Scala Programming.")
    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: