×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

File Handling in Scala

By IncludeHelp Last updated : November 16, 2024

Scala file handling

File handling is storing, excessing and modifying data from in a file. In Scala, we can fetch data from a file, store data in a file in different ways. For this Scala, uses libraries from java, the library used by Scala in file handing is java.io.File.

Now, let's dig into step by step data handing that will clear all things related to file handling in Scala,

Creating a file in Scala and writing content to it

As Scala, uses Java library the libraries of java methods are used.

In this program to will create a new file called by file myfile.txt and then write one sentence in the file.

Program to create a file in Scala

import java.io._

object WriteFileExample { 
    def main(args: Array[String]): Unit = {
        // creating file object
        val file = new File("myfile.txt" )  
        
        //creating object of the PrintWrite 
        //by passing the reference to the file
        val pw = new PrintWriter(file)  
        
        //writing text to the file
        pw.write("Welcome @ IncludeHelp\n")
        pw.write("writing text to the file\n")
        
        //closing the PrintWriter
        pw.close()    
        println("PrintWriter saved and closed...")
    } 
}

Output

PrintWriter saved and closed...

Reading Content line by line in Scala

You can alternatively read the contents of a file in Scala line by line,

Example

import scala.io.Source

object MainObject{
    def main(args:Array[String]){
        //file name
        val filename = "myfile.txt"  
        
        //file reading - creating object name by passing
        //filename i.e. file object
        val filereader = Source.fromFile(filename)  
        //printing characters
        for(line<-fileSource.getLines){  
            println(line)  
        }   
        //closing
        filereader.close()  
    } 
}  

Output

Welcome @ IncludeHelp
writing text to the file

Code Explanation

The program uses the scala.io.Source class to use the getLines method that returns a single line of the code.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.