Scala 文件 I/O
讲解 Scala 复用 java.io.PrintWriter/File 写文件、使用 scala.io.StdIn.readLine 读取控制台输入(替代已废弃 Console.readLine),以及利用 scala.io.Source.fromFile 读取文件并规范关闭句柄。
学完这一章,你能够
- 讲解 Scala 复用 java.io.PrintWriter/File 写文件、使用 scala.io.StdIn.readLine 读取控制台输入(替代已废弃 Console.readLine),以及利用 scala.io.Source.fromFile 读取文件并规范关闭句柄。
使用 java.io 写入文本文件
Scala 标准库未重复封装底层文件写入器,文件写操作通常直接复用 `java.io.File`、`java.io.PrintWriter` 或 `java.nio.file.Files`。创建 `val writer = new PrintWriter(new File("test.txt"), "UTF-8")` 后调用 `writer.write(...)` 写入文本,最后务必在 `finally` 或 `scala.util.Using` 块中调用 `writer.close()` 刷新缓冲并释放文件描述符,显式指定 UTF-8 编码还能避免跨平台中文乱码。
读取控制台标准输入与 Source.fromFile 读文件
接收终端交互输入时,引入 `scala.io.StdIn` 并调用 `StdIn.readLine()` 读取整行文本。需注意自 Scala 2.11 起旧接口 `Console.readLine` 已正式废弃并在后续版本移除,所有新代码均应统一使用 `scala.io.StdIn.readLine()`。
读取本地文本文件可使用 `scala.io.Source.fromFile("test.txt", "UTF-8")`:对返回的 `BufferedSource` 可用 `.foreach(print)` 逐字符输出,或用 `.getLines()` 按行惰性迭代。工程实践中切记不要写成未关闭的匿名 `Source.fromFile(...).foreach(...)` 链式调用,而应通过 `Using(Source.fromFile(...)) { src => ... }` 或 `try ... finally source.close()` 确保及时关闭底层文件句柄,防止句柄泄漏。
离线校验临时目录 UTF-8 文件写入、StdIn 读取与 Source 句柄关闭
"""Offline Scala semantic verification lab for Chapter 25 (file-io)."""
import io
import json
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_write_text_file_in_tempdir():
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "test.txt"
content = "蓝色天空网 Scala 教程"
with target.open("w", encoding="utf-8") as writer:
writer.write(content)
read_back = target.read_text(encoding="utf-8")
expected = {"exists": True, "content": content, "byte_len": len(content.encode("utf-8"))}
actual = {"exists": target.exists(), "content": read_back, "byte_len": target.stat().st_size}
return {
"name": "write_text_file_in_tempdir",
"summary": "在隔离临时目录模拟 PrintWriter 写入 UTF-8 文本文件并关闭后回读校验",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_stdin_readline_simulation():
# Simulate scala.io.StdIn.readLine() (replacement for deprecated Console.readLine since 2.11)
fake_stdin = io.StringIO("https://www.scala-lang.org\n")
line = fake_stdin.readline().rstrip("\r\n")
response = f"谢谢,你输入的是: {line}"
expected = {
"api_since_2_11": "scala.io.StdIn.readLine()",
"deprecated_api": "Console.readLine",
"captured_line": "https://www.scala-lang.org",
"output": "谢谢,你输入的是: https://www.scala-lang.org",
}
actual = {
"api_since_2_11": "scala.io.StdIn.readLine()",
"deprecated_api": "Console.readLine",
"captured_line": line,
"output": response,
}
return {
"name": "stdin_readline_simulation",
"summary": "通过内存流离线模拟 scala.io.StdIn.readLine() 读取交互输入并核对 2.11+ API 迁移",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_source_from_file_read_and_close():
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "sample.txt"
target.write_text("Scala Source.fromFile\nLine 2", encoding="utf-8")
chars = []
fh = target.open("r", encoding="utf-8")
try:
while True:
ch = fh.read(1)
if not ch:
break
chars.append(ch)
finally:
fh.close()
expected = {
"joined": "Scala Source.fromFile\nLine 2",
"char_count": 28,
"handle_closed": True,
}
actual = {
"joined": "".join(chars),
"char_count": len(chars),
"handle_closed": fh.closed,
}
return {
"name": "source_from_file_read_and_close",
"summary": "模拟 Source.fromFile 逐字符 foreach 遍历并在 finally/Using 块中显式关闭文件句柄",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_utf8_multiline_roundtrip_and_cleanup():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "lines.txt"
lines_in = ["第一行:Scala", "第二行:JVM", "第三行:UTF-8"]
p.write_text("\n".join(lines_in), encoding="utf-8")
with p.open("r", encoding="utf-8") as fh:
lines_out = [ln.rstrip("\r\n") for ln in fh]
temp_path_str = str(p)
cleaned = not Path(temp_path_str).exists()
expected = {"line_count": 3, "lines": lines_in, "temp_cleaned": True}
actual = {"line_count": len(lines_out), "lines": lines_out, "temp_cleaned": cleaned}
return {
"name": "utf8_multiline_roundtrip_and_cleanup",
"summary": "验证多行 UTF-8 文本 getLines 往返读取与临时目录退出自动清理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_write_text_file_in_tempdir(),
case_stdin_readline_simulation(),
case_source_from_file_read_and_close(),
case_utf8_multiline_roundtrip_and_cleanup(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中验证隔离临时目录文本写入回读、StdIn.readLine 内存流模拟、Source 逐字符读取并关闭句柄及多行 UTF-8 往返清理全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
当前源码 SHA256:d84cc1b9f480168a16beba002a30150630b628c60f0009f934162ed1b0d52a21
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
ZIP SHA256:9bc3a11505ad2734df6b841c8c085a22370d79ab1b97ef716fd6de8d5ff9e638
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么生产代码中不建议直接写 `Source.fromFile("test.txt").foreach(print)`?更安全的写法是什么?
展开参考解答
因为该单行写法没有持有并关闭 `BufferedSource` 句柄,可能导致操作系统文件描述符泄漏;安全做法是使用 Scala 2.13+ 的 `scala.util.Using(Source.fromFile("test.txt", "UTF-8")) { src => src.getLines().mkString("\n") }` 或在 `try/finally` 中显式调用 `source.close()`。