JAVA使用SFTP操作远程文件

JAVA使用SFTP操作远程文件

1、SFTP驱动

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.51</version>
        </dependency>

2、SFTP工具类

import com.jcraft.jsch.*;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

/**
 * @author: 
 * @version: v1.0
 * @description: SFTP传输工具类 使用ssh登录服务器并上传下载文件
 * @date: 2021-06-08
 **/
public class JschSFTPUtils {

    private static Logger log = Logger.getLogger(JschSFTPUtils.class);


    /**
     * 连接sftp
     *
     * @param user
     * @param password
     * @param port
     * @param hostname
     * @return
     */
    public static ChannelSftp getSftpClient(String user, String password, int port, String hostname) {
        log.info("获取SFTP连接,正在连接服务器。。。。");
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(user, hostname, port);
            if (password != null && password.length() > 0) {
                sshSession.setPassword(password);
            }
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // sshSession 记得关闭
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            log.info("连接服务器成功。。。。");
        } catch (JSchException e) {
            log.info("连接服务器失败。。。。");
        }
        return sftp;
    }


    /**
     * 检查文件是否存在
     *
     * @param sftp
     * @param filePath
     * @return
     */
    public static boolean checkExists(ChannelSftp sftp, String filePath) {

        boolean isExist = false;

        int index = filePath.lastIndexOf("/");
        String fileName = filePath.substring(index + 1);
        String parentDirPath = filePath.substring(0, index + 1);

        Vector files = null;
        try {
            files = listFiles(sftp, parentDirPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iterator = files.iterator();
        while (iterator.hasNext()) {
            ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) iterator.next();
            if (fileName.equals(lsEntry.getFilename())) {
                isExist = true;
                break;
            }
        }
        return isExist;
    }

    /**
     * 上传文件
     *
     * @param sftp
     * @param localFilePath
     * @param goalDirPath
     */
    public static void uploadFile(ChannelSftp sftp, String localFilePath, String goalDirPath) {
        try {
            // 判断目录是否存在
            if (!checkExists(sftp, goalDirPath)) {
                sftp.mkdir(goalDirPath);
            }
            sftp.cd(goalDirPath);
            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            sftp.put(new FileInputStream(localFile), fileName);
            log.info("上传文件成功,文件名:" + localFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件失败,文件名:" + localFilePath);
        }
    }


    /**
     * 上传文件
     *
     * @param sftp
     * @param localFilePath
     * @param goalDirPath
     */
    public static void upload(ChannelSftp sftp, String localFilePath, String goalDirPath) {
        try {
            sftp.cd(goalDirPath);
            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            sftp.put(new FileInputStream(localFile), fileName);
            log.info("上传文件成功,文件名:" + localFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件失败,文件名:" + localFilePath);
        }
    }


    /**
     * 获取目录下的所有文件
     *
     * @param sftp
     * @param dirPath
     * @return
     */
    public static Vector listFiles(ChannelSftp sftp, String dirPath) {

        Vector files = null;
        try {
            files = sftp.ls(dirPath);
        } catch (Exception e) {
            log.info("获取文件或目录失败。。。");
        }
        return files;
    }


    /**
     * 下载文件
     *
     * @param sftp
     * @param downloadFilePath
     * @param goalDirPath
     */
    public static void downloadFile(ChannelSftp sftp, String downloadFilePath, String goalDirPath) {
        try {
            if (checkExists(sftp, downloadFilePath)) {
                File downloadFile = new File(downloadFilePath);
                File goalFile = new File(goalDirPath, downloadFile.getName());
                FileOutputStream os = new FileOutputStream(goalFile);
                sftp.get(downloadFilePath, os);
            } else {
                log.info("文件【" + downloadFilePath + "】不存在~~");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param sftp
     * @param dirPath
     * @param filePath
     */
    public static void deleteFile(ChannelSftp sftp, String dirPath, String filePath) {
        try {
            sftp.cd(dirPath);
            sftp.rm(filePath);
        } catch (SftpException e) {
            e.printStackTrace();
        }

    }


    /**
     * 关闭sftp
     *
     * @param sftp
     */
    public static void close(ChannelSftp sftp) {
        try {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.getSession().disconnect();
                    sftp.disconnect();
                }
            }
        } catch (Exception e) {
            log.info("关闭sftp失败");
        }
        log.info("关闭sftp成功");
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值