Scala File IO – Write File, Read File

Filed Under: Scala

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 file io, scala read file, scala write file

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 Read File

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.

Comments

  1. pikachu pikapika says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

  2. Bugs Bunny says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

  3. KondaiahSinha says:

    why you read file every time for single operation….is it possible to read into a variable and perform the operations on that variable

  4. Dumil says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

  5. Nalinda says:

    HI Pankaj,
    Thank you. This is very help full for me

  6. KundiChekkan says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

  7. Hendi Santika says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

  8. sreenivas says:

    Hi Pankaj , yours all tutorials are excellent. those are very help full to me. Thank you so much.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages