3

我想知道我与 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;
}
}
4

2 回答 2

2

如果我们查看它显示的文档logout()disconnect() 我还建议为您的方法名称 disConnect 提供更好的命名约定,它应该只是 disconnect(FtpClient client, 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;
    }
}
于 2012-06-06T13:21:38.697 回答
1

您可能想查看来自 apache commons 项目的 FtpClient: FtpClient。javaDoc 包含一些精心设计的示例。

于 2012-06-06T13:45:54.420 回答