Bootstrap

SFTP上传和下载

这里使用的是

com.jcraft:jsch:0.1.55

首先连接

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();
}

上传

 FileInputStream in = null;
        try {
            File file = new File(localFile);
            in = new FileInputStream(file);
            sftp.put(localFile本地文件, remotePath上传文件, new MyprogressMonitor());
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }

下载

try {
    sftp.cd(remotePath下载服务器文件夹);
    mkdirs(localPath下载本地地址);
    sftp.get(remoteFileName服务器文件名, localPath本地文件名, new MyprogressMonitor());
} catch (SftpException e) {
    e.printStackTrace();
}

创建目录

public void mkdirs(String path) {
    File f = new File(path);
    String fs = f.getParent();
    f = new File(fs);
    if (!f.exists()) {
        f.mkdirs();
    }
}

上传和下载的监听:

public class MyprogressMonitor implements SftpProgressMonitor {
    @Override
    public void init(int op, String src, String dest, long max) {
        fileSize = max;
        Log.e(TAG, "init: ==============begin===========" + src + "\n======max=======" + max + "\n=======dest========" + dest);

    }

    @Override
    public boolean count(long count) {
        transfered += count;
        Log.e(TAG, "count: ================" + transfered);
        ("文件下载中:" + transfered);
        if (transfered == fileSize) {
          ("下载完成")
        }
    }

    @Override
    public void end() {
        Log.e(TAG, "end: ====================end");
    }

}
;