Updated April 20, 2023
Introduction to Scala Write to File
The purpose to file is that we can easily store and retrieve our data from file when needed. Like any other programming languages scala also provide us way to handle file. By using this we can write, read, open and create a file in scala. But in scala we use java library to write in a file because scala does not provide writing to file. So we can import java.io._ package from java library to write in a file because scala standard library does not contains any class to write. Also if we want we can first importjava.io.File or java.io.PrintWriter.
Syntax:
To write in a file we will use PrintWriter from java.io package. To use this we have to pass our file object inside it. After that we can use PrintWriter object to write in a file. Let’s see a simple syntax to write in a file. See below;
valvariable_name = new PrintWriter("name_of_file")
variable_name.write("Text here!")
In the above syntax for writing in a file. First we have to create a variable which is going to hold the object for PrintWriter class and inside this we have to pass our file object. Immediately after the object creation we can call write() method and provide our text there which we want to write in a file. Below you can see one syntax for beginners for better understanding.
Example:
val pw = new PrintWriter(file_name)
pw.write("My text !! Hello world!! My first example to write in a file.")
How to Write to File in Scala?
Scala does not provide any class to write in a file. For this we have to use existing java library for this because as we know scala is very flexible to use any java object. So to write in a file we make use of print writers class from java library. If we want to use this in our program so we would require including import java.io._ or java.io.PrintWriter package and then only we can make its object otherwise it will give us compile-time error. But scala provide us support for reading from a file for this we can use scala.io.Source package into our program.
Now we will see one practice example for writing to a file in scala for better understanding and will understand its flow as well in details see below;
Example:
importjava.io.PrintWriter
importjava.io.File
object WriteDemo
{
def main(args:Array[String])
{
val file = new File("myfile.txt )
val pw = new PrintWriter(file)
pw.write("My text here!! hello !!")
pw.close()
}
}
In the above example first we are creating the object of file and this file object will create the myfile.txt if not exists in system we can also give path of the existing file from the system but this path should be accurate otherwise we will receive an exception sayingfileNotFound exception. After successful creating of file we are creating the PrintWriter object and passing the reference of our file object inside it.
We can do it in one more way like as follows;
val pw = new PrintWriter(new File("myFile.txt"))
Immediately after this we calling write() method to write in our file and at last we are closing the object of PrintWriter. It helps us preventing our data form external use.
It contains some methods which are mentioned below:
- String getAbsolutePath(): to get absolute path
- booleancanExecute()
- booleanexists(): File exists
- booleancanWrite(): to write
- booleandelete(): to delete
- booleanequals(Object obj): compare two objects
- booleancanRead(): to read
Below are some information related to write text to a file;
Operation | Create | Write | Write Method |
Write | New File() | PrintWriter | PrintWriter.write() |
Points to Remember: 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 user Print Writer to write into a file.
Examples of Scala Write to File
Following are the examples are given below:
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
valmyfile = new File("I:\\demo.txt" )
// Creating printwriter object to parse file
valmyPrintWriter = 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 example we will read the file that we have created recently but not we will read the file line by line not all at once. Also here we are using getLines() method which is available in scala source package to read the file line by line not all at once.
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.
valfileName = "myfile.txt"
//passing file object here
valfileSourec = Source.fromFile(fileName)
println(“pitting the line by line from file !!”)
//using getLines method to print the line by line .
for(textLines<-fileSourec.getLines)
{
println(textLines)
}
// closing the source object to prevent from external use
fileSourec.close()
}
Output:
Example #3
In this example we are reading from the file that we have created previously. Please import scala.io to work. This is the one way that we read from the program itself.
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.
valmyfile = "demo.txt"
// making instance of iterable.
valsrc = Source.fromFile(myfile)
while (src.hasNext)
{
println(src.next)
}
// closing file after read
src.close()
}
Output:
Conclusion
To write in a file in scala we import the java libraries form java.io package. Scala has support for reading from a file. So in order to work with file handling we first create a file, then we write to a file and at last, we read from a file or we can also read the existing file from the system by providing its full path.
Recommended Articles
We hope that this EDUCBA information on “Scala Write to File” was beneficial to you. You can view EDUCBA’s recommended articles for more information.