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