使用JSch工具实现本地与Linux服务器之间文件的上传与下载

一、JAVA连接至Linux服务器

        创建Maven项目,导入JSCH依赖:

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

        编写创建和关闭连接的方法,之后的使用中,只需要调着两个方法即可。连接原理:创建session对话,使用ip、port、userName、password进行校验,函数返回session对话对象。

//jsch创建连接
public static Session getJSchSession(String ip , int port, String userName, String password){
    JSch jSch = new JSch();
    Session session = null;
    try {
        //创建连接
        session = jSch.getSession(userName,ip,port);
        session.setPassword(password);
        //是否使用密钥登录,一般默认为no
        session.setConfig("StrictHostKeyChecking", "no");
        //启用连接
        session.connect();
        System.out.println("==============服务器连接成功==============");
    }catch (Exception e){
        e.printStackTrace();
        System.out.println("==============服务器连接失败==============");
    }
    return session;
}


//jsch关闭连接
public static void closeJSchSession(Session session){
    if (session != null) {
        try {
            session.disconnect();
            System.out.println("===========服务器连接关闭成功===========");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("===========服务器连接关闭失败===========");
        }
    }
}

二、JAVA实现本地与Linux服务器之间的文件上传与下载

        重点:本地往Linux服务器上传主要靠put方法,Linux服务器向本地上传主要是靠get方法。

1、实现本地往Linux服务器上传文件

public void uploadFile(Session session, String remotePath, String localFilePath, String fileName){
        ChannelSftp channel = null;
        InputStream inputStream = null;
        try {
            channel = (ChannelSftp)session.openChannel("sftp");
            channel.connect();
            if(StringUtils.isNotBlank(remotePath)){
                channel.cd(remotePath);
            }
            inputStream = new FileInputStream(localFilePath);
            channel.put(inputStream,fileName);
        } catch (JSchException | SftpException | FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if(channel!=null){
                channel.disconnect();
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭文件流异常",e.getMessage());
                }
            }
        }
    }

解释:

  • session:连接成功后获得的session对象。

  • remotePath:Linux目的地路径,该方法中会首先进入到该路径。

  • localFilePath:本地需要上传的文件地址路径,注意:这个示例是通过流实现的上传,那么该路径一定以文件结尾。

  • fileName:在Linux服务器上面最终上传文件的名字。

2、实现本地下载Linux服务器上的文件

public void downloadFile(Session session, String remotePath, String localFilePath) {
        InputStream inputStream = null;
        ChannelSftp channelSftp = null;
        FileOutputStream outputStream = null;
        try {
            // 调用jsch工具的sftp通道得到yaml文件的流
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            inputStream = channelSftp.get(remotePath, (SftpProgressMonitor)null);
            outputStream = new FileOutputStream(localFilePath);
            byte[] buffer = new byte[1024];
            int readCount;
            while ((readCount = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, readCount);
            }
        } catch (JSchException | SftpException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (channelSftp != null){
                channelSftp.disconnect();
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭文件流异常",e.getMessage());
            }
        }
    }

解释:

  • session:连接成功后获得的session对象。

  • remotePath:Linux目的文件路径,该路径结尾为文件。

  • localFilePath:本地的文件地址路径,如无该文件将自动创建,必须以文件结尾。

  • SftpProgressMonitor:下载进度对象,一般不需要,用来显示下载进度。

        结语:JSch工具是一个非常好用的工具,并且get和put实现本地与Linux服务器之间文件上传与下载的时候,有多种方式,以上只是两种示例,供参考。

        关于JSch工具本地执行Linux命令:Java中使用JSCH工具连接Linux服务器及执行多条Shell命令_java jsch执行本地linux命令-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值