Scala File i/o: Open, Read and Write a File in Scala

1. Scala File io  – Objective

In this tutorial Scala File io, we will learn how to Open, read and write files in Scala. I also recommend you to go through the Scala Syntax and Scala Functions Articles to clear your basics on Scala.

So, let’s start Scala File io Tutorial.

Scala File io: Open, Read and Write a File in Scala

Scala File io: Open, Read and Write a File in Scala

2. Opening and Writing to a File in Scala

We don’t have a class to write a file, in the Scala standard library, so we borrow java.io._ from Java. Or you could import java.io.File and java.io.PrintWriter.

a. The Import

C:\Users\lifei>cd Desktop
C:\Users\lifei\Desktop>scala

Welcome to Scala 2.12.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).

Type in expressions for evaluation. Or try :help.

scala> import java.io._
import java.io._

Learn: Scala Data Types with Examples

b. Creating a New File in Scala

To create a new file to write to, we create a new instance of PrintWriter, and pass a new File object to it.

scala> val writer=new PrintWriter(new File("demo1.txt"))
writer: java.io.PrintWriter = java.io.PrintWriter@31c7c281

c. Writing to the File in Scala

Now, to write to the file, we call the method write() on the object we created.

scala> writer.write("This is a demo")

d. Finally

At this point, nothing is really visible in the file. To see these changes reflect in the file demo1.txt, we need to close it with Scala.

scala> writer.close()

Now, when we check the file demo1.txt again, we find:

This is a demo

Together, the code looks something like this:

C:\Users\lifei>cd Desktop
C:\Users\lifei\Desktop>scala

Welcome to Scala 2.12.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).

Type in expressions for evaluation. Or try :help.

scala> import java.io._
import java.io._
scala> val writer=new PrintWriter(new File("demo1.txt"))
writer: java.io.PrintWriter = java.io.PrintWriter@31c7c281
scala> writer.write("This is a demo")
scala> writer.close()

Learn: Scala Variables with Examples

Scala Quiz

3. Reading From a File in Scala

Now Scala does provide a class to read files. This is the class Source. We use its companion object to read files. For this demonstration, we’re going to read what we put in the file demo1.txt. Let’s begin.

a. The Import

The class we need to import here is scala.io.Source.

scala> import scala.io.Source
import scala.io.Source

b. Reading From the File

To read the contents of this file, we call the fromFile() method of class Source- with the filename as argument. On this, we call the method mkString, like we’ve seen in different collections so far.

scala> Source.fromFile("demo1.txt").mkString
res4: String = This is a demo

c. Reading Between The Lines (Pun Intended)

To read individual lines instead of the whole file at once, we can use the getLines() method. For this,  we change the contents of our file to this:

This is a demo

This is line 2

And this is line 3

The code we use is:

scala> Source.fromFile("demo1.txt").getLines.foreach{x=>println(x)}

This is a demo

This is line 2

And this is line 3

Learn: Scala String Interpolation

d. Using an Iterator

We can also make use of an iterator to get one line at a time:

scala> val it=Source.fromFile("demo1.txt").getLines()
it: Iterator[String] = non-empty iterator
scala> it.next()
res9: String = This is a demo
scala> it.next()
res10: String = This is line 2
scala> it.next()
res11: String = And this is line 3
scala> it.next()
java.util.NoSuchElementException: next on empty iterator
 at scala.collection.Iterator$$anon$2.next(Iterator.scala:38)
 at scala.collection.Iterator$$anon$2.next(Iterator.scala:36)
 at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scala:79)
 at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scala:64)
 ... 28 elided

e. Extracting Individual Lines with take()

When we talked iterators, we saw the use of the method take(n) to return the first n values from the iterator. This is what we’re going to use here.

scala> val it=Source.fromFile("demo1.txt").getLines.take(2)
it: Iterator[String] = non-empty iterator
scala> while(it.hasNext){print(it.next())}

This is a demoThis is line 2

If we passed 1 to take(), it would only print “This is a demo”.

f. Extracting Individual Lines with slice(start,until)

The method slice(start,until) returns an iterator over lines start to until-1.

scala> val it=Source.fromFile("demo1.txt").getLines.slice(1,3)
it: Iterator[String] = non-empty iterator
scala> while(it.hasNext){print(it.next())}

This is line 2And this is line 3

So, this was all on Scala File io Tutorial. Hope you like our explanation.

4. Conclusion

So this is how you read and write a Scala file io. In this article, we saw use of methods write(), close(), fromFile(), getLines(), take(), and slice(). Furthermore, if you have any query, feel free to ask in the comment section.

For Reference

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.