java FTP上传下载文件

1.maven依赖

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

2.代码

package com.demo.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: FtpUtil
 * Description: FTP工具类
 */
public class FtpUtil {
    /**
     * 初始化FTP连接
     *
     * @param ftpClient ftpClient
     * @param host      host
     * @param port      port
     */
    private static void init(FTPClient ftpClient, String host, String port) {
        try {
            ftpClient.setControlEncoding("utf-8");
            ftpClient.connect(ParamUtil.host, Integer.parseInt(ParamUtil.port));//连接服务器
            ftpClient.login(ParamUtil.username, ParamUtil.password);//登录
            int replyCode = ftpClient.getReplyCode();//获得响应码
            System.out.println("replyCode:" + replyCode);
            if (!FTPReply.isPositiveCompletion(replyCode)) {//检查是否响应positive,所有2开头的都是positive
                System.out.println("connect failed ... ftp服务器:" + ParamUtil.host + ":" + ParamUtil.port);
            } else {
                System.out.println("connect successful ... ftp服务器:" + ParamUtil.host + ":" + ParamUtil.port);
            }
        } catch (IOException e) {
            System.out.println("FTP服务器初始化异常");
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param host       host
     * @param port       port
     * @param file       file
     * @param remotePath 远程目录
     * @param remoteName 远程文件名称
     * @return boolean
     */
    public static boolean uploadFile(String host, String port, File file, String remotePath, String remoteName) {
        long startTime = System.currentTimeMillis();
        boolean result = false;
        FTPClient ftpClient = null;
        InputStream inputStream = null;
        try {
            ftpClient = new FTPClient();
            //1. 初始化Ftp连接
            init(ftpClient, host, port);
            //2. 目录若是不存在则创建
            createFtpDir(ftpClient, remotePath);
            ftpClient.changeWorkingDirectory(remotePath);//改变ftp临时会话的当前的工作目录
            //3.上传文件
            ftpClient.setBufferSize(1024 * 1024);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            inputStream = new FileInputStream(file);
            result = ftpClient.storeFile(remoteName, inputStream);
            System.out.println("XML文件:" + remoteName + (result ? "上传成功" : "上传失败"));
            System.out.println("上传耗时:" + (System.currentTimeMillis() - startTime) / 1000.0);
        } catch (IOException e) {
            System.out.println("上传功能异常");
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭流异常");
                }
            }
            close(ftpClient);
        }
        return result;
    }

    /**
     * 批量下载文件
     *
     * @param host       host
     * @param port       port
     * @param remotePath 远程目录
     * @param nameList   远程文件名称集合
     * @return 下载成功文件地址集合
     */
    public static List<String> downloadFiles(String host, String port, String remotePath, List<String> nameList, String localDir) {
        List<String> localList = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            //1. 初始化Ftp连接
            init(ftpClient, host, port);
            //2. 目录若是不存在则创建
            boolean changeFlag = ftpClient.changeWorkingDirectory(remotePath);//改变ftp临时会话的当前的工作目录
            if (!changeFlag) {
                System.out.println("没能在FTP服务器找到该目录:" + remotePath);
            }
            //遍历该目录下的所有文件
            FTPFile[] ftpFiles = ftpClient.listFiles();
            //3.下载文件
            for (FTPFile ftpFile : ftpFiles) {
                String ftpFileName = ftpFile.getName();
                if (nameList.contains(ftpFileName)) {
                    File localDirFile = new File(localDir);
                    if (!localDirFile.exists()) {
                        localDirFile.mkdirs();
                    }
                    String localPath = localDir + "/" + ftpFileName;
                    File localFile = new File(localPath);
                    OutputStream outputStream = new FileOutputStream(localFile);
                    boolean downloadFlag = ftpClient.retrieveFile(ftpFileName, outputStream);
                    if (downloadFlag) {
                        System.out.println("文件:" + ftpFileName + "下载成功");
                        localList.add(localPath);
                        if ("true".equals(ParamUtil.isDelete)) {
                            ftpClient.deleteFile(ftpFileName); //下载成功删除服务器文件
                        }
                    }
                    outputStream.close();
                }
            }
            System.out.println("下载耗时:" + (System.currentTimeMillis() - startTime) / 1000.0);
            return localList;
        } catch (IOException e) {
            System.out.println("下载功能异常");
            e.printStackTrace();
        } finally {
            close(ftpClient);
        }
        return localList;
    }
    
    /**
     * 关闭FTP链接
     * @param ftpClient FTPClient
     */
    private static void close(FTPClient ftpClient) {
        if (ftpClient != null) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("关闭FTP Server异常");
            }
        }
    }

    /**
     * 创建FTP目录(可创建多层)
     * @param ftpClient FTPClient
     * @param path path
     * @return boolean
     * @throws IOException e
     */
    private static boolean createFtpDir(FTPClient ftpClient, String path) throws IOException {
        /* 如果 FTP 连接已经关闭,或者连接无效,则直接返回 */
        if (!ftpClient.isConnected() || !ftpClient.isAvailable()) {
            System.out.println("FTP连接已经关闭或者连接无效");
            return false;
        }
        String directory = path + "/";
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory)) {
            int start = 0;

            if (directory.startsWith("/")) {
                start = 1;
            }
            int end = directory.indexOf("/", start);
            String pathOne = "";
            String pathTwo = "";
            do {
                String subDirectory = new String(path.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
                pathOne = pathOne + "/" + subDirectory;
                if (!existFile(ftpClient, pathOne)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    }
                } else {
                    ftpClient.makeDirectory(subDirectory);
                }
                pathTwo = pathTwo + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
            } while (end > start);
        }
        return true;
    }

    /**
     * 判断文件目录是否存在
     *
     * @param path
     * @return
     */
    private static boolean existFile(FTPClient ftpClient, String path) {
        boolean flag = false;
        /* 如果 FTP 连接已经关闭,或者连接无效,则直接返回 */
        if (!ftpClient.isConnected() || !ftpClient.isAvailable()) {
            System.out.println("FTP连接已经关闭或者连接无效");
            return flag;
        }
        try {
            FTPFile[] fileArr = ftpClient.listFiles(path);
            if (fileArr.length > 0) {
                flag = true;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return flag;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值