Scala Lesson 48 – File Handling | Dataplexa

File Handling in Scala

In this lesson, you will learn how to read from and write to files in Scala. File handling is a fundamental skill used in real-world applications such as logging, configuration management, data processing, and report generation.

Scala provides multiple ways to work with files by leveraging the Java IO and NIO libraries while keeping the code concise and expressive.


Why File Handling Is Important

Almost every production application needs to interact with files for tasks such as:

  • Reading configuration files
  • Processing large datasets
  • Writing logs and reports
  • Importing and exporting data

Reading Files in Scala

The simplest way to read a file in Scala is using scala.io.Source.

import scala.io.Source

val source = Source.fromFile("example.txt")
val content = source.mkString
source.close()

println(content)

This reads the entire file content as a single string. Always remember to close the file after reading.


Reading Files Line by Line

For large files, it is better to process them line by line.

import scala.io.Source

for (line <- Source.fromFile("example.txt").getLines()) {
  println(line)
}

This approach is memory-efficient and commonly used in data processing.


Using Try-Finally for Safety

To ensure resources are always released, use try-finally.

import scala.io.Source

val source = Source.fromFile("example.txt")
try {
  for (line <- source.getLines()) {
    println(line)
  }
} finally {
  source.close()
}

Writing Files in Scala

Scala uses java.io.PrintWriter to write data to files.

import java.io.PrintWriter

val writer = new PrintWriter("output.txt")
writer.println("Hello, Scala!")
writer.println("File writing example")
writer.close()

This creates a file if it does not exist and overwrites it if it does.


Appending to a File

To append data instead of overwriting, use FileWriter.

import java.io.FileWriter

val writer = new FileWriter("output.txt", true)
writer.write("Appending new line\n")
writer.close()

Reading Files with Java NIO

Java NIO provides faster and more flexible file operations.

import java.nio.file.{Files, Paths}

val path = Paths.get("example.txt")
val lines = Files.readAllLines(path)

lines.forEach(println)

Writing Files with Java NIO

NIO also supports writing files efficiently.

import java.nio.file.{Files, Paths}
import java.nio.charset.StandardCharsets

val path = Paths.get("nio-output.txt")
Files.write(path, "Hello from NIO".getBytes(StandardCharsets.UTF_8))

Handling File Errors

File operations may fail due to missing files or permission issues. Use Try for safe handling.

import scala.util.Try
import scala.io.Source

val result = Try(Source.fromFile("missing.txt").mkString)

result match {
  case scala.util.Success(data) => println(data)
  case scala.util.Failure(err)  => println(err.getMessage)
}

Practical Example: Copy File Content

The example below reads content from one file and writes it to another.

import scala.io.Source
import java.io.PrintWriter

val source = Source.fromFile("input.txt")
val writer = new PrintWriter("copy.txt")

try {
  source.getLines().foreach(writer.println)
} finally {
  source.close()
  writer.close()
}

Best Practices

  • Always close file resources
  • Use line-by-line processing for large files
  • Handle exceptions properly
  • Prefer NIO for high-performance use cases

📝 Practice Exercises


Exercise 1

Read a text file and print each line.

Exercise 2

Write user input to a file.

Exercise 3

Copy content from one file to another.


✅ Practice Answers


Answer 1

Source.fromFile("file.txt").getLines().foreach(println)

Answer 2

new PrintWriter("data.txt").println("Scala File")

Answer 3

Files.write(
  Paths.get("copy.txt"),
  Files.readAllBytes(Paths.get("file.txt"))
)

What’s Next?

In the next lesson, you will learn about Database Connections and how Scala applications interact with databases.