EngiLipi › Computer Science › Programming Languages › Scala › I/O, Files & Regular Expressions I/O, Files & Regular Expressions 22.1 Console println("output"); print("no newline"); printf("%d items%n", 3)
System.err.println("error")
val line = scala.io.StdIn.readLine("Name: ")
val n = scala.io.StdIn.readInt()22.2 Files with scala.io.Source import scala.io.Source
import scala.util.Using
val content = Using.resource(Source.fromFile("data.txt"))(_.mkString)
Using.resource(Source.fromFile("data.txt")) { src =>
src.getLines().filter(_.nonEmpty).foreach(println)
}
Source.fromURL("https://example.com").mkString
Source.fromResource("config.txt")22.3 Writing files (java.nio) import java.nio.file.{Files, Paths, StandardOpenOption}
import java.nio.charset.StandardCharsets.UTF_8
Files.writeString(Paths.get("out.txt"), "hello\n")
Files.writeString(Paths.get("log.txt"), "more\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND)
Files.readAllLines(Paths.get("out.txt"))
Files.exists(Paths.get("x")), Files.createDirectories(Paths.get("a/b")), Files.list(Paths.get("."))22.4 os-lib (Li Haoyi — ergonomic file & process API) //> using dep com.lihaoyi::os-lib:0.11.3
os.write(os.pwd / "out.txt", "hello")
os.read(os.pwd / "out.txt")
os.read.lines(os.pwd / "data.csv")
os.list(os.pwd), os.walk(os.pwd), os.remove.all(os.pwd / "tmp")
os.copy(src, dest), os.move(src, dest), os.makeDir.all(os.pwd / "a" / "b")
os.proc("git", "status").call().out.text()22.5 Regular expressions val email = """(\w+)@([\w.]+)""".r
email.findFirstIn("contact: [email protected] ") // Some("[email protected] ")
email.findAllIn("[email protected] [email protected] ").toList
email.findFirstMatchIn("[email protected] ").map(_.group(2)) // Some("x.com")
email.replaceAllIn("[email protected] ", m => s"${m.group(1)} at ${m.group(2)}")
"[email protected] ".matches("""\w+@[\w.]+""")
val Phone = raw"(\d{3})-(\d{4})".r
"555-1234" match { case Phone(a, b) => a + b }22.6 Process execution import scala.sys.process.*
val out = "ls -l".!! // capture output
val code = "ls".! // exit code
(Seq("echo", "hi") #| Seq("tr", "a-z", "A-Z")).!!