java从远程FTP主机下载文件

用到的工具:

  • idea
  • java
  • maven

idea新建maven工程(省略)

在pom文件中引入需要的包

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.9.0</version>
    </dependency>

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>sqljdbc4</artifactId>
        <version>4.0</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>2.0.32</version>
    </dependency>

</dependencies>

新建类SNFTPClient

public class SNFTPClient {
    private FTPClient ftpClient;

    /**
     * 实例化
     * @param host FTP服务器地址
     * @param port FTP服务器端口
     * @param userName FTP登录账户
     * @param password FTP登录密码
     * @param encode 解码
     * @throws IOException
     */
    public SNFTPClient(String host,int port,String userName,String password,String encode) throws IOException{
        ftpClient = new FTPClient();
        //设置传输命令的超时
        ftpClient.setDefaultTimeout(20000);//毫秒
        //设置两个服务连接超时时间
        ftpClient.setConnectTimeout(10000);//毫秒
        //被动模式下设置数据传输的超时时间
        ftpClient.setDataTimeout(15000);//毫秒
        //被动模式(需要设置在连接之前)
        ftpClient.setControlEncoding(encode);
        //连接FTP
        ftpClient.connect(host, port);
        //更加账户密码登录服务
        ftpClient.login(userName, password);
        //被动模式(需要设置在连接之后,尤其linux环境)
        ftpClient.enterLocalPassiveMode();
    }

    /**
     * FTP文件下载
     * @param remoteDirectory 要下载的目录(FTP服务器目录)
     * @param localDirectory 本地下载文件路径
     * @param downloadFileName 下载的文件名
     * @return pair
     */
    public Pair<Boolean,String> downloadFile(String remoteDirectory, String localDirectory, String downloadFileName){
        OutputStream out = null;
        try {
            if (StringUtils.isBlank(downloadFileName)) {
                return Pair.of(false, "要下载的文件不能为空");
            }
            //工作目录切换到下载文件的目录下
            if (!ftpClient.changeWorkingDirectory(remoteDirectory)) {
                return Pair.of(false, "目录不存在");
            }
            //获取目录下所有文件
            FTPFile[] files = ftpClient.listFiles();
            if (files.length < 1) {
                return Pair.of(false, "目录为空");
            }
            boolean fileExist = false;
            boolean downloadFlag = false;
            //遍历文件列表
            for (FTPFile ftpFile : files) {
                String localFile = localDirectory + File.separator + downloadFileName;
                //是否存在要下载的文件
                if (downloadFileName.equals(ftpFile.getName())) {
                    fileExist = true;
                    out = new FileOutputStream(localFile);
                    //下载
                    downloadFlag = ftpClient.retrieveFile(downloadFileName, out);
                    int replyCode = ftpClient.getReplyCode();
                    break;
                }
            }
            if (!fileExist) {
                return Pair.of(false, "FTP服务器上文件不存在");
            }
            return Pair.of(downloadFlag, downloadFlag ? "下载成功" : "下载失败");
        } catch (Exception e) {
            return Pair.of(false, "下载文件异常");
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void close(){
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

调用

/**
 * 下载文件(需要传入解码规则)
 * @param host FTP服务器地址
 * @param port FTP服务器端口
 * @param userName FTP登录账户
 * @param password FTP登录密码
 * @param remoteDirectory 要下载的目录(FTP服务器目录)
 * @param localDirectory 本地下载文件路径
 * @param downloadFileName 下载的文件名
 * @param encode 解码
 * @return pair
 * @throws IOException
 */
public static Pair<Boolean, String> download(String host, int port, String userName, String password, String remoteDirectory, String localDirectory, String downloadFileName, String encode) throws IOException{
	SNFTPClient snftpClient = new SNFTPClient(host, port, userName, password,encode);
	Pair<Boolean, String> pair = snftpClient.downloadFile(remoteDirectory, localDirectory, downloadFileName);
	snftpClient.close();
	return pair;
}

打包成jar包供别处调用

将以下加入到pom文件中,然后执行mvn package

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <filters>
                            <filter>
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>

                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>SNFTPClient.exec</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
THE END