FtpUtil

  1. FTP
  2. SFTP

FTP

package com.jeequan.jeepay.zx.utils;

import cn.hutool.core.io.FileUtil;
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.*;

/**
 * ftp上传下载工具类
 */
public class FtpUtil {

    private static final String host = "139.186.133.191";
    private static final int port = 21;
    private static final String username = "vsftp";
    private static final String password = "******";
    private static final String basePath = "/installed/vsftp";
    private static final String filePath = "/";

    public static boolean uploadFile(String filename, File file) {
        return uploadFile(host, port, username, password, basePath, filePath, filename, FileUtil.getInputStream(file));
    }

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param host     FTP服务器hostname
     * @param port     FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            // 切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                // 如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir))
                        continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            // 设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            // 上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;

        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    public static boolean downloadFile(String fileName, String localPath) {
        return downloadFile(host, port, username, password, basePath, fileName, localPath);
    }

    public static void main(String[] args) {
//      boolean flag = uploadFile("J0003280000000010016012022062001.ZIP", new File("C:\\Users\\tso\\Downloads\\J0003280000000010016012022062001.ZIP"));
//      System.out.println(flag);

        System.err.println(downloadFile("J0003280000000010016012022062001.ZIP", "D:\\360Downloads"));
    }
}

SFTP

package com.jeequan.jeepay.zx.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Properties;

/**
 * @author MEliuak
 * @date 2021/01/07 18:17
 */
@Slf4j
@Component
@RefreshScope
public class SftpUtil {
    /**
     * description: count-> 连接超过次数,线程休眠
     */
    private static final long count = 10;
    /**
     * description: sleepTime-> 休眠时间
     */
    private static final long sleepTime = 6000;

    /**
     * description: count1-> 已经连接次数
     */
    private static long count1 = 0;

    private static final String host = "139.186.133.191";
    private static final int port = 21;
    private static final String username = "vsftp";
    private static final String password = "******";

    public static void main(String[] args) {
        System.err.println(upload(new File("C:\\Users\\tso\\Downloads\\J0003280000000010016012022062001.ZIP"), null, "J0003280000000010016012022062001.ZIP"));
    }

    /**
     * description: 连接sftp服务器
     *
     * @return com.jcraft.jsch.ChannelSftp
     * @author MEliuak
     */
    public static ChannelSftp connect() {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            log.info("Session created ... UserName=" + username + ";host=" + host + ";port=" + port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            log.info("Session connected ...");
            //协议
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            log.info("登录成功");
        } catch (Exception e) {
            try {
                count1 += 1;
                if (count == count1) {
                    throw new RuntimeException(e);
                }
                Thread.sleep(sleepTime);
                log.info("重新连接....");
                connect();
            } catch (InterruptedException e1) {
                throw new RuntimeException(e1);
            }
        }
        return sftp;
    }

    /**
     * description: 关闭 流
     *
     * @param ins  输入流
     * @param file MultipartFile 转 File的文件
     * @return void 返回类型
     * @author MEliuak
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description: 上传文件
     *
     * @param file      要上传的文件
     * @param directory 上传的目录
     * @return Boolean
     * @author MEliuak
     */
    public static Boolean upload(MultipartFile file, String directory, String fileName) {

        ChannelSftp sftp = connect();
        try {
            if (ObjectUtil.isNotNull(directory)) {
                sftp.cd(directory);
            }
        } catch (SftpException e) {
            try {
                sftp.mkdir(directory);
                sftp.cd(directory);
                log.info("创建的路径为--:" + directory);
            } catch (SftpException e1) {
                throw new RuntimeException("ftp创建文件路径失败" + directory);
            }
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            sftp.put(inputStream, fileName);
            ;


        } catch (Exception e) {

            throw new RuntimeException("sftp异常" + e);
        } finally {
            disConnect(sftp);
            closeStream(inputStream, null);
        }
        return true;
    }

    public static Boolean upload(File file, String directory, String fileName) {
        ChannelSftp sftp = connect();
        try {
            if (ObjectUtil.isNotNull(directory)) {
                sftp.cd(directory);
            }
        } catch (SftpException e) {
            try {
                sftp.mkdir(directory);
                sftp.cd(directory);
                log.info("创建的路径为--:" + directory);
            } catch (SftpException e1) {
                throw new RuntimeException("ftp创建文件路径失败" + directory);
            }
        }
        InputStream inputStream = null;
        try {
            inputStream = FileUtil.getInputStream(file);
            sftp.put(inputStream, fileName);
            ;
            log.info("sftp文件上传成功");
        } catch (Exception e) {
            throw new RuntimeException("sftp异常" + e);
        } finally {
            disConnect(sftp);
            closeStream(inputStream, null);
        }
        return true;
    }

    /**
     * description: 上传多个文件
     *
     * @param file      要上传的文件
     * @param directory 上传的目录
     * @param sftp      sftp连接对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author MEliuak
     */
    public static void uploadList(MultipartFile file, String directory, ChannelSftp sftp, String fileName) {
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            try {
                sftp.mkdir(directory);
                sftp.cd(directory);
                log.info("创建的路径为--:" + directory);
            } catch (SftpException e1) {
                throw new RuntimeException("ftp创建文件路径失败" + directory);
            }
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            sftp.put(inputStream, fileName);
            log.info("文件上传成功");
        } catch (Exception e) {
            throw new RuntimeException("sftp异常" + e);
        } finally {
            closeStream(inputStream, null);
        }
    }

    /**
     * description: 下载文件
     *
     * @param directory       下载目录
     * @param downloadFileUrl 下载的文件名称
     * @return byte[]
     * @author MEliuak
     */
    public static byte[] download(String directory, String downloadFileUrl) {
        ChannelSftp sftp = connect();
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //进到文件夹下
            sftp.cd(directory);
            if (log.isInfoEnabled()) {
                log.info("打开远程文件:[{}]", new Object[]{directory});
            }
            InputStream inputStream = sftp.get(downloadFileUrl);
            byteArrayOutputStream = new ByteArrayOutputStream();
            int n = 0;
            byte[] data = new byte[1024];
            while ((n = inputStream.read(data, 0, data.length)) != -1) {
                byteArrayOutputStream.write(data, 0, n);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info("文件下载出现异常,[{}]", e);
            }
            throw new RuntimeException("文件下载出现异常,[{}]", e);
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            disConnect(sftp);
        }
    }

    /**
     * description: 关闭流
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     * @return void
     * @author MEliuak
     */
    private static void closeStream(InputStream inputStream, OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * description: 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @return void 返回类型
     * @author MEliuak
     */
    public static void delete(String directory, String deleteFile) {
        ChannelSftp sftp = null;
        try {
            sftp = connect();
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            disConnect(sftp);
        }
    }

    /**
     * description: 断掉连接
     *
     * @param sftp sftp实体类
     * @return void 返回类型
     * @author MEliuak
     */
    public static void disConnect(ChannelSftp sftp) {
        try {
            sftp.disconnect();
            sftp.getSession().disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

日夜颠倒头发少 ,单纯好骗恋爱脑 ,会背九九乘法表 ,下雨只会往家跑 ,搭讪只会说你好 ---- 2050781802@qq.com

×

喜欢就点赞,疼爱就打赏

相册 说点什么