使用依赖包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); } } } }