java sftp上传实现

注:需要java1.7以上支持

引用jar包 commons-logging-1.2.jar,commons-vfs2-2.2.jar

之前用jsch做了sftp上传的功能,由于用户的openssl版本高,需要改配置,但处于安全考虑又不允许修改,所以选用apache的commons来实现文件的上传,一下直接上代码:

 public static boolean startSFTP(String host,String username,String password,String localFilePath,String remoteFilePath){
        File file = new File(localFilePath);
        if (!file.exists()){
            throw new RuntimeException("Error. localfile is not found");
        }
        StandardFileSystemManager manager = new StandardFileSystemManager();
        try {
            manager.init();
            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder configBuilder = SftpFileSystemConfigBuilder.getInstance();
            configBuilder.setStrictHostKeyChecking(opts,"no");
            configBuilder.setUserDirIsRoot(opts,true);
            configBuilder.setTimeout(opts,10000);
            String sftpUri = "sftp://"+username+":"+password+"@"+host+"/"+remoteFilePath;
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());
            FileObject remoteFile = manager.resolveFile(sftpUri,opts);
            remoteFile.copyFrom(localFile,Selectors.SELECT_SELF);
            System.out.println("File upload successful");
        } catch (FileSystemException e) {
            e.printStackTrace();
        }finally {
            manager.close();
        }
        return true;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值