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.Usingto automatically close resources -
Process every character in a file
-
Treat a
Stringas aFile, 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:
valresult:String="ls -al".!!valresult=Seq("ls","-al").!!valrootProcs=("ps aux"#|"grep root").!!.trimvalcontents:LazyList[String]=sys.process.Process("find /Users -print").lazyLines
The Scala process DSL provides five primary ways to execute external commands:
-
Use the
runmethod to run ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access