java实现SFTP上传下载

导入maven依赖

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

代码实习 

package cn.headradio.supernova.monitoring.service.ftp;

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.apache.log4j.Logger;

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

/**
 * sftp工具类
 *
 * @author chuanyuerenhai
 * @version 1.0
 * @date 2023年9月27日15:15:11
 */
public class SFTPUtils {

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

    private String host;//服务器连接ip

    private String username;//用户名

    private String password;//密码

    private int port = 22;//端口号

    private ChannelSftp sftp = null;

    private Session sshSession = null;

    public SFTPUtils() {
    }

    public SFTPUtils(String host, int port, String username, String password) {

        this.host = host;

        this.username = username;

        this.password = password;

        this.port = port;

    }

    public SFTPUtils(String host, String username, String password) {

        this.host = host;

        this.username = username;

        this.password = password;

    }

    /**
     * 通过SFTP连接服务器
     */

    public void connect() {

        try {

            JSch jsch = new JSch();

            jsch.getSession(username, host, port);

            sshSession = jsch.getSession(username, host, port);

            if (log.isInfoEnabled()) {

                log.info("Session created.");

            }

            sshSession.setPassword(password);

            Properties sshConfig = new Properties();

            sshConfig.put("StrictHostKeyChecking", "no");

            sshSession.setConfig(sshConfig);

            sshSession.connect();

            if (log.isInfoEnabled()) {

                log.info("Session connected.");

            }

            Channel channel = sshSession.openChannel("sftp");

            channel.connect();

            if (log.isInfoEnabled()) {

                log.info("Opening Channel.");

            }

            sftp = (ChannelSftp) channel;

            if (log.isInfoEnabled()) {

                log.warn("Connected to " + host + ".");

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**
     * 关闭连接
     */

    public void disconnect() {

        if (this.sftp != null) {

            if (this.sftp.isConnected()) {

                this.sftp.disconnect();

                if (log.isInfoEnabled()) {

                    log.info("sftp is closed already");

                }

            }

        }

        if (this.sshSession != null) {

            if (this.sshSession.isConnected()) {

                this.sshSession.disconnect();

                if (log.isInfoEnabled()) {

                    log.info("sshSession is closed already");

                }

            }

        }

    }

    /**
     * 批量下载文件
     *
     * @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
     * @param del:下载后是否删除sftp文件
     * @return
     */

    public void batchDownLoadFile(String remotePath, String localPath, boolean del) {

        try {

            Vector v = listFiles(remotePath);
            if (v.size() > 0) {
                log.warn("本次处理文件个数不为零,开始下载...fileSize=" + (v.size() - 2));

                Iterator it = v.iterator();

                while (it.hasNext()) {

                    LsEntry entry = (LsEntry) it.next();

                    String filename = entry.getFilename();
                    if (".".equals(filename) || "..".equals(filename)) {
                        continue;
                    }
                    SftpATTRS attrs = entry.getAttrs();

                    if (!attrs.isDir()) {
                        //下载成功标志
                        boolean flag;

                        flag = downloadFile(remotePath, filename, localPath, filename);
                        if (flag) {

                            if (flag && del) {
                                deleteSFTP(remotePath, filename);
                            }
                        }
                    } else {
                        //进入子目录
                        String newRemotePath = remotePath + "/" + filename;
                        String newLocalPath = localPath + File.separator + filename;
                        batchDownLoadFile(newRemotePath, newLocalPath, true);
                    }
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
        }

    }

    /**
     * 下载单个文件
     *
     * @param remotePath:远程下载目录(以路径符号结束)
     * @param remoteFileName:下载文件名
     * @param localPath:本地保存目录(以路径符号结束)
     * @param localFileName:保存文件名
     * @return
     */

    public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {

        FileOutputStream fieloutput = null;
        try {

            if (remotePath != null && !"".equals(remotePath)) {

                sftp.cd(remotePath);

            }

            File file = new File(localPath + File.separator + localFileName);

            if (!file.getParentFile().exists()) {

                file.getParentFile().mkdirs();

            }


            fieloutput = new FileOutputStream(file);
            sftp.get(remoteFileName, fieloutput);


            return true;

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (SftpException e) {

            e.printStackTrace();

        } finally {

            if (null != fieloutput) {

                try {

                    fieloutput.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return false;

    }

    /**
     * 上传单个文件
     *
     * @param remotePath:远程保存目录
     * @param remoteFileName:保存文件名
     * @param localPath:本地上传目录(以路径符号结束)
     * @param localFileName:上传的文件名
     * @return
     */

    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {

        FileInputStream in = null;

        try {

            createDir(remotePath);

            File file = new File(localPath + localFileName);

            in = new FileInputStream(file);

            sftp.put(in, remoteFileName);

            return true;

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (SftpException e) {

            e.printStackTrace();

        } finally {

            if (in != null) {

                try {

                    in.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return false;

    }


    /**
     * 删除本地文件
     *
     * @param filePath
     * @return
     */

    public boolean deleteFile(String filePath) {

        File file = new File(filePath);

        if (!file.exists()) {

            return false;

        }

        if (!file.isFile()) {

            return false;

        }

        boolean rs = file.delete();

        if (rs && log.isInfoEnabled()) {

            log.info("delete file success from local.");

        }

        return rs;

    }

    /**
     * 创建目录
     *
     * @param createpath
     * @return
     */

    public boolean createDir(String createpath) {

        try {

            if (isDirExist(createpath)) {

                this.sftp.cd(createpath);

                return true;

            }

            String pathArry[] = createpath.split("/");

            StringBuffer filePath = new StringBuffer("/");

            for (String path : pathArry) {

                if (path.equals("")) {

                    continue;

                }

                filePath.append(path + "/");

                if (isDirExist(filePath.toString())) {

                    sftp.cd(filePath.toString());

                } else {

                    // 建立目录
                    sftp.mkdir(filePath.toString());

                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());

                }

            }

            this.sftp.cd(createpath);

            return true;

        } catch (SftpException e) {

            e.printStackTrace();

        }

        return false;

    }

    /**
     * 判断目录是否存在
     *
     * @param directory
     * @return
     */

    public boolean isDirExist(String directory) {

        boolean isDirExistFlag = false;

        try {

            SftpATTRS sftpATTRS = sftp.lstat(directory);

            isDirExistFlag = true;

            return sftpATTRS.isDir();

        } catch (Exception e) {

            if (e.getMessage().toLowerCase().equals("no such file")) {

                isDirExistFlag = false;

            }

        }

        return isDirExistFlag;

    }

    /**
     * 删除stfp文件
     *
     * @param directory:要删除文件所在目录
     * @param deleteFile:要删除的文件
     */

    public void deleteSFTP(String directory, String deleteFile) {

        try {
//            sftp.cd(directory);

            sftp.rm(deleteFile);


        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**
     * 如果目录不存在就创建目录
     *
     * @param path
     */

    public void mkdirs(String path) {

        File f = new File(path);

        String fs = f.getParent();

        f = new File(fs);

        if (!f.exists()) {

            f.mkdirs();

        }

    }

    /**
     * 列出目录下的文件
     *
     * @param directory:要列出的目录
     * @return
     * @throws SftpException
     */

    public Vector listFiles(String directory) throws SftpException {

        return sftp.ls(directory);

    }

    public String getHost() {

        return host;

    }

    public void setHost(String host) {

        this.host = host;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public int getPort() {

        return port;

    }

    public void setPort(int port) {

        this.port = port;

    }

    public ChannelSftp getSftp() {

        return sftp;

    }

    public void setSftp(ChannelSftp sftp) {

        this.sftp = sftp;

    }

    /**
     * 下载文件
     */

    public void downloadFiles(String localPath, String sftpPath, String host, int port, String userName, String password) {

        SFTPUtils sftp = new SFTPUtils(host, port, userName, password);
        ;

        try {
            //建立链接
            sftp.connect();

            // 下载
            sftp.batchDownLoadFile(sftpPath, localPath, true);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            sftp.disconnect();

        }

    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值