scalaintermediate

File I/O Read and Write Operations

Read and write files in Scala: text files, CSV parsing, JSON handling, and resource management.

scala
import scala.io.Source
import java.io.{File, PrintWriter, BufferedWriter, FileWriter}
import java.nio.file.{Files, Paths, StandardOpenOption}
import scala.util.{Using, Try}

@main def run(): Unit =
  // Write text file
  val writer = PrintWriter("output.txt")
  try
    writer.println("Line 1")
    writer.println("Line 2")
    writer.println("Line 3")
  finally
    writer.close()

  // Using (auto-close) - Scala 2.13+
  Using(PrintWriter("output2.txt")) { w =>
    w.println("Auto-closed line 1")
    w.println("Auto-closed line 2")
  }

  // Read entire file
  val content = Using(Source.fromFile("output.txt")) { source =>
    source.mkString
  }
  println(s"Content: $content")

  // Read lines
  val lines = Using(Source.fromFile("output.txt")) { source =>
    source.getLines().toList
  }
  lines.foreach(ls => ls.foreach(l => println(s"  > $l")))

  // Read CSV
  Using(PrintWriter("data.csv")) { w =>
    w.println("name,age,city")
    w.println("Alice,30,NYC")
    w.println("Bob,25,LA")
    w.println("Carol,35,Chicago")
  }

  case class Person(name: String, age: Int, city: String)

  val people = Using(Source.fromFile("data.csv")) { source =>
    source.getLines()
      .drop(1)  // skip header
      .map(_.split(","))
      .collect {
        case Array(name, age, city) =>
          Person(name.trim, age.trim.toInt, city.trim)
      }
      .toList
  }
  people.foreach(ps => ps.foreach(println))

  // Append to file
  Using(BufferedWriter(FileWriter("output.txt", true))) { w =>
    w.write("\nAppended line")
  }

  // Check file existence
  val path = Paths.get("output.txt")
  println(s"Exists: ${Files.exists(path)}")
  println(s"Size: ${Files.size(path)} bytes")

  // List directory
  val dir = File(".")
  val txtFiles = dir.listFiles().filter(_.getName.endsWith(".txt"))
  txtFiles.foreach(f => println(s"  ${f.getName} (${f.length()} bytes)"))

  // NIO write
  Files.writeString(
    Paths.get("nio-output.txt"),
    "Written with NIO\nLine 2"
  )

  // Cleanup
  List("output.txt", "output2.txt", "data.csv", "nio-output.txt")
    .foreach(f => Files.deleteIfExists(Paths.get(f)))

Use Cases

  • Reading configuration files
  • CSV data parsing
  • Log file processing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.