"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
入口文件:projects/scala-file-io-lab/explore-file-io.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-file-io.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2418.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip