作者專注於Java、架構、Linux、小程序、爬蟲、自動化等技術。 工作期間含淚整理出一些資料,微信搜索【javaUp】,回復 【java】【黑客】【爬蟲】【小程序】【面試】等關鍵字免費獲取資料。技術交流、項目合作可私聊。 微信:shuhao-99999
使用依賴包commons-net:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
java代碼里面使用上面依賴包中的FTPClient;
通過四個參數連接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);
}
}
}
}