Java——通过Java代码连接ftp服务器

编程知识 更新时间:2023-04-07 06:31:45

作者专注于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.apachemons.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apachemons.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);
            }
        }
    }
}

更多推荐

Java——通过Java代码连接ftp服务器

本文发布于:2023-04-07 06:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/38d3df52745cd77dea638bc62010b7a9.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   服务器   Java   ftp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 52535文章数
  • 14阅读数
  • 0评论数