Java实现sftp上传一个目录下的所有文件到Linux服务器

参考来自:https://blog.csdn.net/g5628907/article/details/78281864

使用JSch实现SFTP文件传输

https://www.cnblogs.com/itmanxgl/p/fe5d33512609fe540eb08a76e3c4db3a.html

JSch - Java实现的SFTP(文件上传详解篇)

http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html


Maven依赖



    com.jcraft
    jsch
    0.1.54




    org.hamcrest
    hamcrest-all
    1.3
    test

实现代码:

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;

import java.io.File;

public class SftpUtil {

    private SftpUtil() {
    }

    public static void uploadFilesToServer(String srcPath, String dst, SftpProgressMonitor monitor) throws Exception {
        ChannelSftp sftp = upload(srcPath, dst, monitor);
        if (sftp != null) {
            sftp.quit();
            sftp.disconnect();
            System.out.println(" SFTP disconnect successfully!");
        }
        ChannelSftpSingleton.getInstance().closeChannel();
    }


    private static ChannelSftp upload(String path, String dst, SftpProgressMonitor monitor) throws SftpException {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        ChannelSftp chSftp = null;
        try {
            chSftp = ChannelSftpSingleton.getInstance().getChannelSftp();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        if (chSftp == null) {
            return null;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length <= 0) {
                return null;
            }
            for (File f : files) {
                String fp = f.getAbsolutePath();
                if (f.isDirectory()) {
                    String mkdir = dst + "/" + f.getName();
                    try {
                        chSftp.cd(mkdir);
                    } catch (Exception e) {
                        chSftp.mkdir(mkdir);
                    }
                    upload(fp, mkdir, monitor);
                } else {
                    chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
                }
            }
        } else {
            String fp = file.getAbsolutePath();
            chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
        }
        return chSftp;
    }

}
import com.jcraft.jsch.*;

import java.util.Properties;

public class ChannelSftpSingleton {

    private static ChannelSftpSingleton instance;
    private ChannelSftp channelSftp;
    private Session session;

    private ChannelSftpSingleton() {
    }

    public static ChannelSftpSingleton getInstance() {
        if (instance == null) {
            instance = new ChannelSftpSingleton();
        }
        return instance;
    }

    public ChannelSftp getChannelSftp() throws JSchException {
        if (channelSftp != null) {
            return channelSftp;
        }
        channelSftp = getChannel();
        return channelSftp;
    }

    /**
     * 断开SFTP Channel、Session连接
     *
     * @throws Exception
     */
    public void closeChannel() throws Exception {
        if (channelSftp != null) {
            channelSftp.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        System.out.println("disconnected SFTP successfully!");
    }

    /**
     * 获得SFTP Channel
     *
     * @return ChannelSftp Instance
     * @throws JSchException
     */
    private ChannelSftp getChannel() throws JSchException {
        String host = "120.**.***.***";
        int port = 22;
        String userName = "root";
        String password = "123456";
        // 创建JSch对象
        JSch jsch = new JSch();
        // 根据用户名,主机ip,端口获取一个Session对象
        session = jsch.getSession(userName, host, port);
        // 设置密码
        session.setPassword(password);
        Properties configTemp = new Properties();
        configTemp.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(configTemp);
        // 设置timeout时间
        session.setTimeout(60000);
        session.connect();
        // 通过Session建立链接
        // 打开SFTP通道
        Channel channel = session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
        System.out.println("Connected successfully to ftpHost = " + host + ",as ftpUserName = " + userName + ", returning: " + channel);
        return (ChannelSftp) channel;
    }
}

测试

String src = "C:\\Users\\admin\\Desktop\\test";
        String dst = "/usr/local/src/test";
        try {
            SftpUtil.uploadFilesToServer(src, dst, new SftpProgressMonitor() {
                @Override
                public void init(int i, String src, String dst, long size) {
                    System.out.println("正在上传 " + src + " 到 " + dst + ",文件大小:" + (double) (size / 1024) + "kb");
                }

                @Override
                public boolean count(long l) {
                    return true;
                }

                @Override
                public void end() {
                    System.out.println("上传成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

关于session和管道的管理

程序运行, 调用上传时可以实现文件上传, 但是重复上传会报错:
4: java.io.IOException: Pipe closed
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:487)
    at com.hikvison.gg.xupdate.web.modules.test.SftpUtil.upload(SftpUtil.java:55)
    at com.hikvison.gg.xupdate.web.modules.test.SftpUtil.uploadFilesToServer(SftpUtil.java:16)
    at com.hikvison.gg.xupdate.web.modules.controller.TestSftpController.testSftp(TestSftpController.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
  

ChannelSftp sftp = upload(srcPath, dst, monitor);
if (sftp != null) {
    sftp.quit();
    sftp.disconnect();
    System.out.println(" SFTP disconnect successfully!");
}
ChannelSftpSingleton.getInstance().closeChannel();
channelSftpSingleton是static类型, 每次使用后会关闭, 再次使用时提示Pipe closed

将获取ChannelSftp的判断注释掉就可以了

public ChannelSftp getChannelSftp() throws JSchException {
    /*if (channelSftp != null) {
        //channelSftp.connect();
        return channelSftp;
    }*/
    channelSftp = getChannel();
    return channelSftp;
}

后续好好学习下

 

 

 

你可能感兴趣的:(Linux)