user840718
user840718

Reputation: 1611

What's the best practice to close an ftp connection?

I want to avoid System.exit(0) because in my program there is a scheduler that launch this piece of code every day.

FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
        System.out.println("Establishing connection...");
        client.connect(ftpHost, ftpPort);
        System.out.print(client.getReplyString());
        System.out.println("Connection ok.");
        if (client.login(ftpUser, ftpPass)) {
            System.out.println("Login ok");
            System.out.print(client.getReplyString());
            System.out.println("Setting PASV");
            client.enterLocalPassiveMode();
            System.out.print(client.getReplyString());
        } else {
            System.out.println("Login error!");
            System.out.print(client.getReplyString());
        }
        if (client.changeWorkingDirectory("/path/mydir")) {
            System.out.println("Dir changed");
            System.out.print(client.getReplyString());
        } else {
            System.out.println("Error changing dir");
            System.out.print(client.getReplyString());
        }
        //Upload
        fis = new FileInputStream("README.txt");
        if(client.storeFile("README.txt", fis))
        {
            System.out.println("File sent");
            System.out.print(client.getReplyString());
        }
        else
        {
            System.out.println("Error during sending file");
            System.out.print(client.getReplyString());
        }

        if (client.logout()) {
            System.out.println("Logout closed successfully");
            System.out.print(client.getReplyString());
        } else {
            System.out.println("Logout problem");
            System.out.print(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

What I have to use when something goes wrong? Logout? Disconnect? Or other stuffs?

Upvotes: 1

Views: 1163

Answers (1)

DmitryKanunnikoff
DmitryKanunnikoff

Reputation: 2266

client.disconnect(); will be sufficient:

finally {
    if (client.isConnected()) {
        try {
          client.disconnect();
        } catch (IOException ioe) {
          // do nothing
        }
    }
}

See official example.

Upvotes: 1

Related Questions