Scala I/O – How to read a file

 75 total views,  2 views today

Hey guys! Welcome to Scala series. In this tutorial, you will learn How to read a file using Scala I/O api.

In many cases, we might need to read the contents of the file in our program and work on the file to manipulate the data and  play with it.

So Yes, Scala has provided a Scala I/O api to read the file or we can even write to a file. So let us understand how to read a file in our program.

Scala I/O – Read a file as String

At first we need to import an API

import scala.io.Source

This import package will help us to read the required file from our directory.

Create a file

Let us create a file with some contents.

//Create file
touch /tmp/input.txt

//Contents of the file
Hi How are you
Welcome to staticreference.com
Hope you are enjoying our posts
Please do subcribe to get latest updates on our site
Please do provide your valuable comments and feedback to improve our site.
Thanks

Ok so we have created a file with contents.Now let us dive into our code and see how we can read contents of input.txt.

/**
 * Scala I/O - How to read a file
 */
package com.scala

import scala.io.Source

object StaticReference {

  def main(args: Array[String]): Unit = {
    
    //Read file
    var file = Source.fromFile("/tmp/input.txt")
    
    //print
    print(file)
  }
}

Output

non-empty iterator

Did you notice the output? It shows non-empty iterator which means we have read the object as iterator and not yet the content. So let us modify the code to read the content as String.

Modified code to read the file contents as String.

/**
 * Scala I/O - How to read a file
 */
package com.scala

import scala.io.Source

object StaticReference {

  def main(args: Array[String]): Unit = {
    
    //Read file
    var file = Source.fromFile("/tmp/input.txt").mkString
    
    //print
    print(file)
  }
}

Output

Hi How are you
Welcome to staticreference.com
Hope you are enjoying our posts
Please do subcribe to get latest updates on our site
Please do provide your valuable comments and feedback to improve our site.
Thanks

So this how we use Source library to read contents of the file.

Let us write a small word count program by reading the file using Scala Source library.

Word count by reading a file

/**
 * Scala I/O - How to read a file(word count)
 */
package com.scala

import scala.io.Source

object StaticReference {

  def main(args: Array[String]): Unit = {

    //Read file
    var file = Source.fromFile("/tmp/input.txt").mkString

    var output = file.split(" ").groupBy(item => item).mapValues(list => list.size)

    //print
    output.foreach(println)
  }
}

Output

(enjoying,1)
(your,1)
(are,2)
(How,1)
(posts
Please,1)
(our,3)
(do,2)
(staticreference.com
Hope,1)
(you
Welcome,1)
(provide,1)
(to,3)
(you,1)
(feedback,1)
(on,1)
(updates,1)
(valuable,1)
(improve,1)
(subcribe,1)
(Hi,1)
(get,1)
(latest,1)
(site.
Thanks
,1)
(site
Please,1)
(and,1)
(comments,1)

Hope you have understood how to read a file.Hey but wait, how to use “non-empty iterator” object . You should be having this question? So let us iterate the object and see what we get as the output.

/**
 * Scala I/O - How to read a file
 */
package com.scala

import scala.io.Source

object StaticReference {

  def main(args: Array[String]): Unit = {
    
    //Read file
    var file = Source.fromFile("/tmp/input.txt")
    
    //print
    file.foreach(print)
  }
}

Output

H
i
 
H
o
w
 
a
r
e
 
y
o
u


W
e
l
c
o
m
e
 
t
o
 
s
t
a
t
i
c
r
e
f
e
r
e
n
c
e
.
c
o
m


H
o
p
e
 
y
o
u
 
a
r
e
 
e
n
j
o
y
i
n
g
 
o
u
r
 
p
o
s
t
s




So this printing each word by word. So that is the reason we used mkString() to read the file as String.

Scala I/O – Read file by each Line

In this example we read the file using Source with getLines() operation.So when we iterate, it reads each line and print it.

/**
 * Scala I/O - How to read a file
 */
package com.scala

import scala.io.Source

object StaticReference {

  def main(args: Array[String]): Unit = {
    
    //Read file
    var file = Source.fromFile("/tmp/input.txt").getLines()
    
    //print
    file.foreach(println)
  }
}

Output

Hi How are you
Welcome to staticreference.com
Hope you are enjoying our posts
Please do subcribe to get latest updates on our site
Please do provide your valuable comments and feedback to improve our site.
Thanks

References: 

 

I hope you like this tutorial and you were able to understand how to read a file in Scala

Thanks for reading and please give us a thumb up and comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.