1

http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html

我注意到 finally 子句中的示例 disconnects() ,但对 logout() 没有做同样的事情

FTPClient ftp = new FTPClient();
FTPClientConfig config = new FTPClientConfig();
config.setXXX(YYY); // change required options
ftp.configure(config );
boolean error = false;
try {
  int reply;
  ftp.connect("ftp.foobar.com");
  System.out.println("Connected to " + server + ".");
  System.out.print(ftp.getReplyString());

  // After connection attempt, you should check the reply code to verify
  // success.
  reply = ftp.getReplyCode();

  if(!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    System.err.println("FTP server refused connection.");
    System.exit(1);
  }
  ... // transfer files
  ftp.logout();
} catch(IOException e) {
  error = true;
  e.printStackTrace();
} finally {
  if(ftp.isConnected()) {
    try {
      ftp.disconnect();
    } catch(IOException ioe) {
      // do nothing
    }
  }
  System.exit(error ? 1 : 0);
}

任何人都知道为什么我们在捕获异常时不需要注销()?

4

2 回答 2

2

任何人都知道为什么我们在捕获异常时不需要注销()?

函数内部代码ftp.logout()如下:

public boolean  logout() throws IOException
{
         return FTPReply.isPositiveCompletion(quit());
}

该函数使用向quit()发送命令。如果发生连接异常,我们可能无法连接. 调用将尝试再次写入 FTP 服务器并创建带有额外抛出异常的资源。另外,虽然函数也会抛出异常,但它会关闭并释放函数不会的资源:从下面的函数源代码中可以看出:sendCommand(FTPCommand.QUIT)FTP ServerFTP Serverlogout()disconnect()input, output, socketlogout()disconnect()

 public void disconnect() throws IOException
 {
      if (_socket_ != null) _socket_.close();
      if (_input_ != null) _input_.close();
      if (_output_ != null) _output_.close();
      if (_socket_ != null) _socket_ = null;
      _input_ = null;
      _output_ = null;
       _controlInput_ = null;
       _controlOutput_ = null;
       _newReplyString = false;
       _replyString = null;
 }
于 2013-10-14T20:56:59.000 回答
0

我对 FTPClient 库知之甚少,但考虑到文档中给出的解释,我相信可以安全地假设与服务器断开连接意味着注销作为该过程的一部分(如果适用):

disconnect() :关闭与 FTP 服务器的连接并将连接参数恢复为默认值。

logout() : 通过发送 QUIT 命令注销 FTP 服务器。

http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html

于 2013-10-14T20:48:53.580 回答