Java如何使用Java代码连接ftp服务器呢?
下文笔者讲述使用java代码连接ftp服务器的方法分享,如下所示
实现思路:
借助commons-net即可实现连接ftp
例:
使用依赖包commons-net
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
借助ftp的相应参数连接ftp服务器
通过四个参数连接ftp:ip、端口、用户名、密码
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
@Service
public class FtpClientManager {
private static Logger logger = LoggerFactory.getLogger(FtpClientManager.class);
@Value("${ftp.ip}")
private String ip;
@Value("${ftp.port}")
private Integer port;
@Value("${ftp.username}")
private String username;
@Value("${ftp.password}")
private String password;
private FTPClient ftpClient = null;
public FTPClient getClient() {
if (this.ftpClient == null) {
this.initClient();
}
return this.ftpClient;
}
private void initClient() {
if (this.ftpClient == null) {
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
ftpClient.login(username, password);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
logger.info("success to connect ftp server");
} catch (IOException e) {
logger.error("faild to connect ftp server because " + e.getMessage());
System.exit(0);
}
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


