Chapter 16. Files and Processes

When it comes to working with files, many of the solutions in this chapter use Java classes, but for some situations the scala.io.Source class and its companion object offer some nice simplifications compared to Java. Not only does Source make it easy to open and read text files, but it also makes it easy to accomplish other tasks, such as downloading content from URLs or substituting a String for a File.

File recipes in this chapter will demonstrate how to:

  • Read and write text and binary files

  • Use the Loan Pattern with scala.util.Using to automatically close resources

  • Process every character in a file

  • Treat a String as a File, typically for the purpose of testing

  • Serialize and deserialize objects to files

  • List files and directories

Next, when it comes to working with processes, the Scala process classes are written as a DSL so you can execute external system commands in a way that feels similar to Unix. The ability to run system commands is useful for applications, and it’s terrific for scripts.

The classes and methods of the scala.sys.process package let you run external system commands from Scala, with code that looks like this:

val result: String = "ls -al".!!
val result = Seq("ls", "-al").!!
val rootProcs = ("ps aux" #| "grep root").!!.trim
val contents: LazyList[String] =
    sys.process.Process("find /Users -print").lazyLines

The Scala process DSL provides five primary ways to execute external commands:

  • Use the run method to run ...

Get Scala Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.