如何使用 ruby​​ 判断 FTP 文件是否存在?

发布于 2024-11-19 11:32:34 字数 462 浏览 7 评论 0原文

我正在尝试找出判断文件是否存在于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨巷深深 2024-11-26 11:32:34

我认为你的方法似乎很好,除了一件事:并非所有 FTP 服务器都支持 SIZE 命令,它是在 FTP 扩展,因此无法保证。正如您自己所注意到的,您的异常处理也有点粗糙。我建议专门拯救FTPReplyError。如果它告诉您 SIZE 未实现(500 或 502),您可能应该依赖后备,更多的是在更新代码之后:

def remote_exists?(idx)
  ftp = Net::FTP.new(FTP_SERVER)
  ftp.login
  begin
    ftp.size(idx)
  rescue FTPReplyError => e
    reply = e.message
    err_code = reply[0,3].to_i
    unless err_code == 500 || err_code == 502
      # other problem, raise
      raise 
    end
    # fallback solution 
  end
    true
end

一个可行的后备是使用 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 rescue FTPReplyError 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:

def remote_exists?(idx)
  ftp = Net::FTP.new(FTP_SERVER)
  ftp.login
  begin
    ftp.size(idx)
  rescue FTPReplyError => e
    reply = e.message
    err_code = reply[0,3].to_i
    unless err_code == 500 || err_code == 502
      # other problem, raise
      raise 
    end
    # fallback solution 
  end
    true
end

A viable fallback would be to retrieve the list of files with FTP#list, then iterate through them and compare with idx.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文