jon*_*hue 2 ruby ruby-on-rails file readfile ruby-on-rails-4
我正在阅读一个空的 HTML 文件,如下所示:
file = File.read("file_path/file.html", "wb")
Run Code Online (Sandbox Code Playgroud)
为什么会抛出这个 TypeError?
没有将字符串隐式转换为整数
日志:
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)
TypeError (no implicit conversion of String into Integer):
app/controllers/abc_controller.rb:49:in `read'
app/controllers/abc_controller.rb:49:in `build'
Run Code Online (Sandbox Code Playgroud)
如果文件是空的,你到底想读什么?
File#read的第二个参数是可选的,应该是您要从文件中读出的字符串的长度。"wb"不是整数,因此是错误消息。
您使用的参数看起来更像open.
如果你想读取文件,只需使用
content = File.read(filename)
Run Code Online (Sandbox Code Playgroud)
如果你想写它,你可以使用
File.open(filename,'w+') do |file|
file.puts "content"
end
Run Code Online (Sandbox Code Playgroud)
'w+' 是一种文件模式,它:
如果文件存在,则覆盖现有文件。如果文件不存在,则创建一个新文件进行读写。
如果要检查文件是否存在:
File.exists?(filename)
Run Code Online (Sandbox Code Playgroud)
如果要检查现有文件是否为空:
File.size(filename)==0
Run Code Online (Sandbox Code Playgroud)
该文件可能充满空格(大小 > 0,但仍为“空”)。使用导轨:
File.read(filename).blank?
Run Code Online (Sandbox Code Playgroud)