File Handling and Operations in Scala

Reading Time: 3 minutes

Today we will look into Scala File IO operations. So let’s start with the basic definition.

File Handling is a way to store the fetched information in a file. 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.

Creating and Writing to the file

Scala doesn’t provide file writing methods. So, you have to use the Java PrintWriter or FileWriter methods.

The above code will create a text file ScalaFile.txt and contains the string “Hello, This is scala file”.  After creating the file, printWriter is used to write content to this file.

Reading Each Character

Scala does not provide a class to write a file but it provides a class to read the files. This is the class Source of package. We use its companion object to read files

To read the contents of this file, we call the fromFile() method of class Source for reading the contents of the file which includes filename as argument.

You must close the file reference after reading or writing the file by using close() method.

Reading Each Line

Below code will read each line from the file. We can use getLines() method to read individual lines instead of the whole file at once.

Reading from file Example

Handling Exceptions When Writing

Scala treats any exception involved in opening a file such as IOException as a runtime exception. This means that we are not warned of any exception that may be thrown at compile-time.

To avoid this scenario, we should wrap our read operation in a try/catch block. With this approach, we’re sure that any exception that is thrown at runtime is handled.

Handling Exceptions When Reading

 similar to writing files, we should wrap our read operation in a try/catch block.


In this article, we’ve seen how to read from and write to files in Scala, as well as how to handle exceptions and avoid memory leakage by closing resources immediately after use.

Hope this article will help you in getting the basics of file handling in scala, want to explore more in file handling refer link.

Stay tuned for upcoming blogs.

Written by 

Chitra Sapkal is a software consultant at Knoldus Inc. having experience of 2 years. Knoldus does Big Data product development on Scala, Spark, and Functional Java. She is a self-motivated, passionate person who is recognized as a good team player, Her hobbies include playing badminton and travelling.