Updated March 30, 2023
Introduction to Scala File
Scala file handling is quite similar to java. We can use a scala package or we can also use packages provided by java to handle files. We can create, read, write, and open a file in scala similarly we can do in other languages. Scala provides us various methods to create or read, write on file we just need to import proper packages to use those classes, methods, or interfaces. The file is a concept of strong and fetching of our data we can write any lines of data into the file.
Syntax:
val my_file = new File("your_file_name" )
The above syntax shows how we can create a file in our system. We just need to give the variable and file name by which we want to create the file in the system.
Like:
val myfile = new File("demo.txt" )
This will create a file in your system with a specified name.
How File handling work in Scala?
The purpose to use file is that we can easily store and retrieve our data from the file when needed. But to create a file and read from file we must have java.io package import in our Scala Program because in scala we do not have any standards library for writing data to file so for that we need to use java.io. So in java file class, we can either pass a file name or a directory name where we want to create a file. This file class has so many different methods which are working internally to handle the file.
So if you want to create a file object we must follow the below steps;
var myfile = new File("file name")
In this, you can give your filename or directory name. This path can be relative or absolute. This file class also maintains the access permission issues when it comes to the security of files to prevent it from external use. Also, this Java File class is immutable that means once created cannot change.
It has many methods. Some are mentioned below:
- String getAbsolutePath(): to get absolute path
- boolean canExecute()
- boolean exists() : File exists
- boolean canWrite() : to write
- boolean delete() : to delete
- boolean equals(Object obj) : compare two objects
- boolean canRead() : to read
In the scala, we have a scala.io package to handle file events. Also, we can use java package to achieve those same features. Let’s discuss them one by one. Now first we will see how we can write and create a file in scala.
Step 1: To create and write on a file;
import java.io._
val myfile = new File("demo.txt" )
This is the very basic step to start with.
Explanation: In the above line of code, we are creating a file object. File objects have this constructor in which we need to pass the file name. It will create one file with the specified name in the system.
Step 2: This file object is available in the java.io package so we need to import it into our program in order to avoid any errors.
val pr = new PrintWriter(myfile)
Explanation: Now we are using PrintWriter object to parse our file. As the name suggests it has a write a method to write in a file. This is also available inside the java.io package.
Step 3: For this, we need to parse our file into its constructor.
pr.write("We are writing to the file.")
Explanation: PrintWriter has this method to write in the file with specified content.
Step 4:
pr.close()
Explanation: In this step, we are just closing this object.
Below you can find the steps which are required to read data from a file:
Step 1:
val myfile = "demo.txt"
Explanation: In this step, we are just defining the name of the file from which we want to read data.
Step 2:
val src = Source.fromFile(myfile)
Explanation: Now this step is important because here we are using Source class to provide them the file and get the data of the file. It has one method called From File where we need to provide the filename from which we want to read.
Step 3:
for(line<-src.getLines){
println(line)
}
Explanation: To read data we must require a for loop in order to iterate over each and every word of the file. Here we are creating an instance of the iterable file which can easily be iterated.
Step 4:
src.close()
Explanation: In this step, we are just closing the source object. It helps us prevent our data from external use.
Operation | Create | Write | Write Method |
Write | New File() | PrintWriter | PrintWriter.write() |
Operation | Read | To Get file | To get file data |
Read | Filename | Source.fromFile | Get lines() |
Packages to be imported:
1)scala.io >> to read from a file
2)java.io.File >> to write to a file
Points to be remembered:
In Scala, we do not have any library to support the functionality to write in a file. For this, we need to use java.io. File to create and write in a file. Also, we can use Print Writer to write into a file.
Example to Implement Scala File
Below are the examples of Scala File:
Example #1
In this example, we are creating, parsing, and writing to a file.
Code:
import java.io.File
import java.io.PrintWriter
object Main extends App{
// Your code here!
// Creating a file
val myfile = new File("I:\\demo.txt" )
// Creting printwriter obejct to parse file
val myPrintWriter = new PrintWriter(myfile)
// writing data to file
myPrintWriter.write("This is our first content to write into a file.")
// close
myPrintWriter.close()
}
Output:
Example #2
In this file, we are reading from the file that we have created previously. Please import scala.io to work.
Code:
import java.io.File
import java.io.PrintWriter
import scala.io.Source
object Main extends App{
// Your code here!
// mentioning file name from which we need to read.
val myfile = "demo.txt"
// making istance of iteratable.
val src = Source.fromFile(myfile)
while (src.hasNext)
{
println(src.next)
}
// closing file after read
src.close()
}
Output:
Conclusion
Files are used to store our data. In scala, we used two libraries to deal with file handling i.e. Java.io and scala.io. Like any other programming language, we can create, read, and write into a file. The file got created on a particular location if given otherwise it will create into the user folder of our system.
Recommended Articles
This is a guide to Scala File. Here we discuss an introduction to Scala File, syntax, how does it work, examples with code and output. You can also go through our other related articles to learn more –