Reputation: 5348
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html
I noticed the example disconnects() in the finally clause, but doesn't do the same for 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);
}
Anyone know why we don't need to logout() when we catch an exception?
Upvotes: 1
Views: 4896
Reputation: 15418
Anyone know why we don't need to logout() when we catch an exception?
The inside code of ftp.logout()
function is as follows:
public boolean logout() throws IOException
{
return FTPReply.isPositiveCompletion(quit());
}
The quit()
function send a command using sendCommand(FTPCommand.QUIT)
to the FTP Server
. If a connection exception happens, we are likely not being able to connect with FTP Server
. calling logout()
will try to write to FTP server again and create resources with additional throwing exception. In addition, although disconnect()
function will also throw an exception, it closes the input, output, socket
and releases resources which logout()
function doesn't: as it is evident from the following source code of disconnect()
function:
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;
}
Upvotes: 2
Reputation: 1
I dont know much about the FTPClient library but I believe it's safe to assume disconnecting from the server implies logging out as part of the process if applicable, considering the explanations given in the docs:
disconnect() : Closes the connection to the FTP server and restores connection parameters to the default values.
logout() : Logout of the FTP server by sending the QUIT command.
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html
Upvotes: 0