关闭ftp连接的最佳实践是什么?

gblwokeq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(406)

我想避免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();
    }

出了问题我要用什么?注销?断开连接?或者其他东西?

x4shl7ld

x4shl7ld1#

client.disconnect();就足够了:

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

参见官方示例。

相关问题