Scala – File I/O

  • date 28th April, 2021 |
  • by Prwatech |
  • 0 Comments

File Handling in Scala

 

File Handling is an approach to store the fetch data in a file. Scala provides packages from which we can read, open, create and compose the records. To write something in scala we get java.io._ from Java since we don't have a class to write into a file, in the Scala standard library. We could likewise import java.io.File and java.io.PrintWriter.

File handling in Scala involves reading from and writing to files using various APIs and libraries available in the Scala standard library and third-party frameworks. Scala provides convenient and expressive ways to work with files, leveraging features such as pattern matching, functional programming, and type safety.

For basic file I/O operations, Scala's scala.io.Source class allows reading from text files line by line or as a whole. Alternatively, the Java java.io and java.nio packages can be used directly from Scala to work with files, providing low-level file manipulation capabilities.

Scala also supports more advanced file handling scenarios, such as reading and writing binary data using java.io.InputStream and java.io.OutputStream or working with file paths and directories using java.nio.file.Paths and java.nio.file.Files.

Open, Read and Write a File in Scala

use case 1:

scala> import java.io._

import java.io._

scala> val writer=new PrintWriter(new File("demo1.txt"))

2scala> writer.write("This is a Prwatech")

scala> writer.close()

3scala> import scala.io.Source

scala> Source.fromFile("demo1.txt").mkString

use case 2:

scala> import java.io._

import java.io._

scala> val writer=new PrintWriter(new File("Prwatech.txt"))

2scala> writer.write("Big Data ")

scala> writer.write(" Data Science")

4scala> writer.write(" Tableau")

5scala> writer.close()

scala> import scala.io.Source

7scala> Source.fromFile("Prwatech.txt").mkString

 

Quick Support

image image