如何使用 ruby 判断 FTP 文件是否存在?
我正在尝试找出判断文件是否存在于 ftp 服务器上的最佳且最快的方法。
这就是我想出的...
def remote_exists?(idx)
#@file.rewind if @file.eof?
ftp = Net::FTP.new(FTP_SERVER)
ftp.login
begin
ftp.size(idx)
rescue Exception
return false
end
true
end
似乎仅仅捕获每个异常是一个坏主意,但我很难获得正确的特定异常。
我还在代码中使用 OpenURI 来实际获取文件。我试图弄清楚是否有更好的方法,但我认为它只是使用 Net::FTP 无论如何。
I'm trying to figure out the best and fastest way to tell if a file exists on an ftp server.
This is what I came up with...
def remote_exists?(idx)
#@file.rewind if @file.eof?
ftp = Net::FTP.new(FTP_SERVER)
ftp.login
begin
ftp.size(idx)
rescue Exception
return false
end
true
end
It seems like just capturing every exception is a bad idea but I had trouble getting the correct specific exception(s).
I'm also using OpenURI in my code to actually get the file. I was trying to figure out if that might have some method that might be better but I think it just uses Net::FTP anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的方法似乎很好,除了一件事:并非所有 FTP 服务器都支持
SIZE
命令,它是在 FTP 扩展,因此无法保证。正如您自己所注意到的,您的异常处理也有点粗糙。我建议专门拯救FTPReplyError
。如果它告诉您 SIZE 未实现(500 或 502),您可能应该依赖后备,更多的是在更新代码之后:一个可行的后备是使用
FTP# 检索文件列表list
,然后迭代它们并与idx
进行比较。I think your approach seems fine except for one thing: not all FTP servers support the
SIZE
command, it was introduced in the Extensions of FTP, so there's no guarantee. Your exception handling is also a bit coarse, as you noticed yourself. I would suggest to rescueFTPReplyError
specifically. In case it gives you an indication that SIZE is not implemented (500 or 502) you should probably rely on a fallback, more on that after the updated code:A viable fallback would be to retrieve the list of files with
FTP#list
, then iterate through them and compare withidx
.