小智 14
EOFError在所有IO中都很方便,这个类是ruby中所有输入/输出的基础.现在还要记住核心的Unix概念:一切都是文件.这包括套接字.因此,如果您打开某个套接字并正在读取它,则异常情况可能是遇到文件结尾.
所有的例子都显示了EOFError的琐碎用法(在阅读一些文本文件时),这些用法并不实用.但是,开始挖掘net/http或其他大量使用套接字的类,您将看到使用此异常.
编辑从net/ftp添加此示例
def getline
line = @sock.readline # if get EOF, raise EOFError
line.sub!(/(\r\n|\n|\r)\z/n, "")
if @debug_mode
print "get: ", sanitize(line), "\n"
end
return line
end
Run Code Online (Sandbox Code Playgroud)
当您尝试对已经引用文件末尾的文件对象执行操作时,将引发EOFError(文件结束错误).在这个例子中,我们试图readline
在线不存在时.
例如:
import_file = File.open(filename)
begin
while (line = import_file.readline)
sline = FasterCSV.parse_line(line)
# Do stuff with sline
end
rescue EOFError
# Finished processing the file
end
Run Code Online (Sandbox Code Playgroud)
没有EOFError可以实现同样的目的:
File.open(filename).each do |line|
sline = FasterCSV.parse_line(line)
# Do stuff with sline
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17363 次 |
最近记录: |