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 scala.io 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.
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.