gpt4 book ai didi

Java Apache FTPClient API : Why isn't logout() in finally clause?

转载 作者:行者123 更新时间:2023-11-30 04:12:06 25 4
gpt4 key购买 nike

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);
}

有人知道为什么我们在捕获异常时不需要 logout() 吗?

最佳答案

Anyone know why we don't need to logout() when we catch an exception?

内码ftp.logout()功能如下:

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

quit() 函数使用 sendCommand(FTPCommand.QUIT) 将命令发送到 FTP 服务器。如果发生连接异常,我们很可能无法连接FTP服务器。调用 logout() 将尝试再次写入 FTP 服务器并创建资源,并抛出额外的异常。另外,虽然disconnect()函数也会抛出异常,但它会关闭输入、输出、套接字并释放logout()所占用的资源。函数没有:从下面的 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;
}

关于Java Apache FTPClient API : Why isn't logout() in finally clause?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19368912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com