简体   繁体   中英

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?

client.disconnect(); will be sufficient:

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

See official example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM