如何读取 Crystal 语言的文件?

How Do I Read a File in Crystal Lang?

我熟悉 Ruby 并且正在尝试用 Crystal 编写程序。

我有一个名为 special_file.txt 的文件,我想在我的 Crystal 程序中读取它,我该怎么做?

Crystal 受到 Ruby 语法的启发,因此您通常可以以类似的方式读取和执行文件操作。例如,Crystal 有一个包含 read 方法的 File classclass which is an instance of the IO class

要读取文件系统上的文件内容,您可以实例化一个 File 对象并调用来自 IO super class:[=23 的 gets_to_end 方法=]

file = File.new("path/to/file")
content = file.gets_to_end
file.close

gets_to_end 方法将整个 IO 对象数据读取到 String 变量。

您也可以使用块调用来获得类似的结果:

# Implicit close with `open`
content = File.open("path/to/file") do |file|
  file.gets_to_end
end

最后,读取整个文件内容的最惯用的方法是一行:

# Shortcut:
content = File.read("path/to/file")