File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter.
Creating a new file :
- java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
- File(String pathname) converts theparameter string to abstract path name, creating a new file instance.
Writing to the file
- java.io.PrintWriter includes all the printing methods included in PrintStream.
Below is the implementation for creating a new file and writing into it.
A text file abc.txt is created and contains the string “Hello, This is Geeks For Geeks”
Scala does not provide class to write a file but it provide a class to read the files. This is the class Source. 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.
Reading a File
scala.io.Source includes methods for iterable representation of the source file.
Source.fromFile creates a source from the input file.
file.next return the next element in the iteration and moves the iterator one step ahead.
file.hasnext checks if there is next element available to iterate.
getLines– Iterate through file line by line
Below is the implementation for Reading each character from a file.
We can use getLines() method to read individual lines instead of the whole file at once.
Below is the implementation for Reading each line from a file.
- Scala | Exception Handling
- Scala Map
- Scala | Either
- Set in Scala | Set-2
- Set in Scala | Set-1
- TreeSet in Scala
- Scala this keyword
- How to sort a Scala Map by key
- Scala Extractors
- How to get all the keys from a Scala map
- How to get all the values from a Scala map
- Scala sum Map values
- How to sort a Scala Map by value
- Scala | Value Classes
- Scala For Comprehensions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.