zoukankan      html  css  js  c++  java
  • Java——通过Java代码连接ftp服务器

    作者专注于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);
                }
            }
        }
    }
    

  • 相关阅读:
    oracle常用命令
    批量导出docker镜像
    python中的xpath
    __call__, __str__
    闭包
    ORM操作
    nginx跨域请求
    docker-compose命令
    nginx 之 websocket长连接
    nginx--proxy_set_header
  • 原文地址:https://www.cnblogs.com/shuhao66666/p/15196336.html
Copyright © 2011-2022 走看看