最近做了一个sftp服务器文件下载的功能,mark一下:
首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传、下载、删除的方法importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;importjava.util.Properties;importjava.util.Vector;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importcom.jcraft.jsch.Channel;importcom.jcraft.jsch.ChannelSftp;importcom.jcraft.jsch.ChannelSftp.LsEntry;importcom.jcraft.jsch.JSch;importcom.jcraft.jsch.Session;public classSftpClientUtil {/*** 初始化日志引擎*/
private final Logger logger = LoggerFactory.getLogger(SftpClientUtil.class);/**Sftp*/ChannelSftp sftp= null;/**主机*/
private String host = "";/**端口*/
private int port = 0;/**用户名*/
private String username = "";/**密码*/
private String password = "";/*** 构造函数
*
*@paramhost
* 主机
*@paramport
* 端口
*@paramusername
* 用户名
*@parampassword
* 密码
**/
public SftpClientUtil(String host, intport, String username,
String password){this.host =host;this.port =port;this.username =username;this.password =password;
}/*** 连接sftp服务器
*
*@throwsException*/
public void connect() throwsException {
JSch jsch= newJSch();
Session sshSession= jsch.getSession(this.username, this.host, this.port);
logger.debug(SftpClientUtil.class + "Session created.");
sshSession.setPassword(password);
Properties sshConfig= newProperties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(20000);
logger.debug(SftpClientUtil.class + " Session connected.");
logger.debug(SftpClientUtil.class + " Opening Channel.");
Channel channel= sshSession.openChannel("sftp");
channel.connect();this.sftp =(ChannelSftp) ch