ftp文件上传下载

FTP Util

FTP连接

断开连接

文件列表

文件上传下载

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.5</version>
        </dependency>
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
import java.util.*;

/**
 * @date 2023/1/13 15:19
 */
public class FTPUtil {

    private static final Log log = LogFactory.getLog(FTPUtils.class);

    private static final String hostname = "192.168.xx.xxx";
    private static final int port = 21;
    private static final String username = "*****";
    private static final String password = "*****";

    private static String remotePath = "/remotePath/";

    private static String localCharset = "GBK";

    private static String serverCharset = "ISO-8859-1";

    public static final String DIR_NOT_EXIST = "该目录不存在";

    public static final String DIR_CONTAINS_NO_FILE = "该目录下没有文件";



    /**
     * FTPClient对象
     **/
    private static FTPClient ftpClient = null;

    private FTPUtil() {

    }


    /**
     *获取远程文件列表
     * @return
     */
    public static List<String> getFileNameList() {
        ftpClient = new FTPClient();
        FTPFile[] ftpFileArr = null;
        ArrayList<String> fileNameList = new ArrayList<>();
        if (connect(ftpClient, hostname, port, username, password)) {
            try {
                if (ftpClient.changeWorkingDirectory(remotePath)) {
                    ftpFileArr = ftpClient.listFiles(remotePath);
                }
                assert ftpFileArr != null;
                for (FTPFile ftpFile : ftpFileArr) {
                    fileNameList.add(ftpFile.getName());
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return fileNameList;
    }

    /**
     * 上传
     */
    public static boolean upload(String remotePath, String saveName, String localPath) {
        boolean flag = false;
        ftpClient = new FTPClient();

        //1 测试连接
        if (connect(ftpClient, hostname, port, username, password)) {
            try {
                InputStream inputStream = new FileInputStream(localPath);
                //2 检查工作目录是否存在
                if (!ftpClient.changeWorkingDirectory(remotePath)) {
                    ftpClient.makeDirectory(remotePath);
                }
                ftpClient.changeWorkingDirectory(remotePath);
                if (storeFile(ftpClient, saveName, inputStream)) {
                    flag = true;
                    inputStream.close();
                    disconnect(ftpClient);
                }
            } catch (IOException e) {
                log.error("工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 下载
     * @param fileName
     * @param savePath
     * @return
     */
    public static String downloadFiles(String fileName, String savePath) {
        FTPClient ftpClient = new FTPClient();
        connect(ftpClient, hostname, port, username, password);
        if (ftpClient != null) {
            try {
                String path = remotePath + fileName;
                // 判断是否存在该目录
                if (!ftpClient.changeWorkingDirectory(remotePath)) {
                    log.error(path + DIR_NOT_EXIST);
                    return null;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式,开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error(path + DIR_CONTAINS_NO_FILE);
                    return null;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(savePath + ftpName);
                    try (OutputStream os = new FileOutputStream(file)) {
                        ftpClient.retrieveFile(ff, os);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } catch (IOException e) {
                log.error("下载文件失败", e);
            } finally {
                disconnect(ftpClient);
            }
        }
        return savePath+fileName;
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.error("已关闭连接");
            } catch (IOException e) {
                log.error("没有关闭连接");
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
        boolean flag = false;
        try {
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            if (ftpClient.login(username, password)) {
                log.info("连接ftp成功");
                flag = true;
            } else {
                log.error("连接ftp失败,可能用户名或密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败,可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        如/home
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.error("上传成功");
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            log.error("上传失败");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值