如何正确连接和断开FTP服务器?

时间:2012-06-06 13:17:12

标签: java ftp ftp-client

我想知道我与FTP服务器连接和断开连接的方式是否正确或是否更好。

我正在使用sun.net.ftp.FtpClient

import sun.net.ftp.FtpClient;

public class FTPUtility
{
    public static FtpClient connect(FTPConfig ftpConfig,WebTextArea statusTextArea)
    {
        String hostname = ftpConfig.getFtpServer();
        String username = ftpConfig.getUsername();
        String password = ftpConfig.getPassword();
        String portnumb = ftpConfig.getPort();

            try
            {
                FtpClient client = new FtpClient(hostname);
                statusTextArea.append("Connecting to " + hostname + " as " + username + " on port:" + portnumb );
                client.login(username, password);
                client.binary();
                statusTextArea.append("Connected to " + hostname + " as " + username  + " on port:" + portnumb );
                return client;
            }
            catch (Exception e)
            {
                statusTextArea.append("Failed to connect to " + hostname + " as " + username + "\n".concat(e.getMessage()) );
                return null;
            }

    }

public static boolean disConnect(FtpClient client, WebTextArea statusTextArea)
{     
    boolean success = false;
    if (client != null)
    {
        try
        {
            statusTextArea.append("Disconnecting from server...");
            client.closeServer();
            statusTextArea.append("Disconnected from server." );
            success = true;
        }
        catch (Exception e)
        {
            statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
        }
    }

  return success;
}
}

2 个答案:

答案 0 :(得分:1)

如果我们使用logout()disconnect()查看其显示的documentation 我还建议为你的方法名称disConnect建立一个更好的命名约定,它应该断开连接(FtpClient客户端,WebTextArea statusTextArea)(没有大写字母C)

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

如果结束失败,则返回false

catch (Exception e)
    {
        statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
return false;
    }
}

答案 1 :(得分:1)

您可能想要从apache commons项目中查看FtpClient: FtpClient。 javaDoc包含一些很好的例子。