关闭ftp连接的最佳做法是什么?

时间:2015-01-15 14:53:20

标签: java ftp ftp-client

我想避免使用System.exit(0),因为在我的程序中有一个启动它的调度程序 每天都有一段代码。

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

出现问题时我必须使用什么? 登出?断开?还是其他东西?

1 个答案:

答案 0 :(得分:0)

client.disconnect();就足够了:

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

请参阅official example