Files and processes
The file system and the child process are the two ways a command line program reaches outside itself, and both are in the JDK that Scala runs on: java.nio.file.Files for a path, a file and a directory, and ProcessBuilder for a program that is started and waited for. No library is involved, and the resource rules of the lesson on Using apply to both.
Files, directories and bytes
A Path names a file; Files does the work with static methods, and the write names its encoding as UTF-8 instead of relying on the platform default. The program writes in a temporary directory, reads it back, appends to it and lists it:
files.scala
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, StandardOpenOption}
import scala.util.Using
@main def files(): Unit =
val dir = Files.createTempDirectory("scala-course")
val notes = dir.resolve("notes.txt")
try
Files.writeString(notes, "first line\nsecond line\n", StandardCharsets.UTF_8)
println(Files.exists(notes))
println(Files.size(notes))
println(Files.readString(notes).linesIterator.toList)
Files.writeString(notes, "appended\n", StandardOpenOption.APPEND)
println(Files.readAllLines(notes).size())
val names = Using.resource(Files.list(dir)) { stream =>
stream.map(path => path.getFileName.toString).sorted().toList
}
println(names)
finally
Files.deleteIfExists(notes)
Files.deleteIfExists(dir)
scala-cli run --server=false files.scala
true
23
List(first line, second line)
3
[notes.txt]
Files.size counts bytes and not characters: the two lines and their line breaks are twenty-three of them. linesIterator splits the text into lines without asking the file again, and readAllLines returns a list that includes the appended line. Files.list returns a stream that holds the directory open until it is closed, which is why the program wraps it in Using.resource: the listing of a directory is a resource like any other.
A child process and its exit status
ProcessBuilder takes the program and its arguments as separate strings, starts it, and gives back a Process whose output streams and exit status the parent reads. The example runs a shell so that one command can write to both streams and choose its status:
processes.scala
@main def processes(): Unit =
val process = ProcessBuilder("sh", "-c", "echo hi; echo oops 1>&2; exit 3").start()
val stdout = new String(process.getInputStream.readAllBytes(), "UTF-8").trim
val stderr = new String(process.getErrorStream.readAllBytes(), "UTF-8").trim
println(s"stdout: $stdout")
println(s"stderr: $stderr")
println(process.waitFor())
scala-cli run --server=false processes.scala
stdout: hi
stderr: oops
3
The three answers are the child's standard output, its standard error and its exit status. waitFor blocks until the process ends, and the two streams must be read before it: a child that writes more than the pipe buffer holds waits for a reader that never comes, which is the deadlock this shape avoids by reading both first. The command sh -c needs a POSIX shell, so the program runs on Linux, on macOS and on Windows under WSL; on Windows itself the first argument would be cmd with /c.
Related
- Exceptions and Using: the Using.resource that closes the directory stream.
- The HTTP client: the other door to the outside world, over the network.
- Virtual threads: why a blocking read became affordable to write.
- Java: the same two APIs, which Scala uses as they are.
Автор статьи: Arthur Isaev