Java 如何正确连接和断开与FTP服务器的连接?
我想知道我连接和断开FTP服务器的方式是否正确,或者是否可以更好。 我正在使用Java 如何正确连接和断开与FTP服务器的连接?,java,ftp,ftp-client,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.getFtp
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;
}
}
如果我们看一下,它显示使用logout()
和disconnect()
我还建议为方法名disConnect建立一个更好的命名约定,它应该是disConnect(FtpClient客户端,WebTextArea statusTextArea)(无大写字母C)
如果关闭失败,也返回false
catch (Exception e)
{
statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
return false;
}
}
您可能希望从apache commons项目中签出FtpClient: . javaDoc包含一些精心设计的示例
catch (Exception e)
{
statusTextArea.append("Failed to disconnect from server. " + "\n".concat(e.getMessage()));
return false;
}
}