Java SFTP文件上传下载

本文介绍了使用Java通过SFTP协议进行文件上传和下载的方法,包括如何在操作中更改文件名。实现过程中引用了jsch-0.1.54.jar库,并建议将日志系统替换为log4j。
摘要由CSDN通过智能技术生成

Java实现SFTP,上传下载时可以变更文件名,很实用
在安卓文章里看到的,用的包是:jsch-0.1.54.jar,log请换成log4j

public class SFTPUtils {
     

    private String TAG="SFTPUtils";  
    private String host;  
    private String username;  
    private String password;  
    private int port = 22;  
    private ChannelSftp sftp = null;  
    private Session sshSession = null;  

    public SFTPUtils (String host, String username, String password) {  
        this.host = host;  
        this.username = username;  
        this.password = password;  
    }  

    /** 
     * connect server via sftp 
     */  
    public ChannelSftp connect() {  
        JSch jsch = new JSch();  
        try {  
            sshSession = jsch.getSession(username, host, port);  
            sshSession.setPassword(password);  
            Properties sshConfig = new Properties();  
            sshConfig.put("StrictHostKeyChecking", "no");  
            sshSession.setConfig(sshConfig);  
            sshSession.connect();  
            Channel channel = sshSession.openChannel("sftp");  
            if (channel != null) {  
                channel.connect();  
            } else {  
                Log.e(TAG, "channel connecting failed.");  
            }  
            sftp = (ChannelSftp) channel;  
        } catch (JSchException e) {  
            e.printStackTrace();  
        }  
        return sftp;  
    }  


/** 
 * 断开服务器 
 */  
    public void disconnect() {  
        if (this.sftp != null) {  
            if (this.sftp.isConnected()) {  
                this.sftp.disconnect();  
                Log.d(TAG,"sftp is closed already");  
            }  
        }  
        if (this.sshSession != null) {  
            if
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值