import com.jcraft.jsch.*;importorg.apache.commons.io.IOUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;import java.io.*;importjava.util.Properties;importjava.util.Vector;/***@version1.0.0
* @ClassName: SFTPUtil
* @Description: sftp连接工具类*/
public classSFTPUtil {private transient Logger log = LoggerFactory.getLogger(this.getClass());privateChannelSftp sftp;privateSession session;//FTP 登录用户名
privateString userName;//FTP 登录密码
privateString password;//FTP 服务器地址IP地址
privateString host;//FTP 端口
private intport;/*** 构造基于密码认证的sftp对象
*
*@paramuserName
*@parampassword
*@paramhost
*@paramport*/
public SFTPUtil(String userName, String password, String host, intport) {this.userName =userName;this.password =password;this.host =host;this.port =port;
}publicSFTPUtil() {
}/*** 连接sftp服务器
*
*@throwsException*/
public voidlogin() {try{
JSch jsch= newJSch();
log.info("sftp connect by host:{} username:{}", host, userName);
session=jsch.getSession(userName, host, port);
log.info("Session is build");if (password != null) {
session.setPassword(password);
}
Properties config= newProperties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Session is connected");
Channel channel= session.openChannel("sftp");
channel.connect();
log.info("channel is connected");
sftp=(ChannelSftp) channel;
log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
}catch(JSchException e) {
log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", newObject[]{host, port, e.getMessage()});
}
}/*** 关闭连接 server*/
public voidlogout() {if (sftp != null) {if(sftp.isConnected()) {
sftp.disconnect();
log.info("sftp is closed already");
}
}if (session != null) {if(session.isConnected()) {
session.disconnect();
log.info("sshSession is closed already");
}
}
}/*** 递归根据路径创建文件夹
*
*@paramdirs 根据 / 分隔后的数组文件夹名称
*@paramtempPath 拼接路径
*@paramlength 文件夹的格式
*@paramindex 数组下标
*@return
*/
public void mkdirDir(String[] dirs, String tempPath, int length, intindex) {//以"/a/b/c/d"为例按"/"分隔后,第0位是"";顾下标从1开始
index++;if (index
tempPath += "/" +dirs[index];
}try{
log.info("检测目录[" + tempPath + "]");
sftp.cd(tempPath);if (index
mkdirDir(dirs, tempPath, length, index);
}
}catch(SftpException ex) {
log.warn("创建目录[" + tempPath + "]");try{
sftp.mkdir(tempPath);
sftp.cd(tempPath);
}catch(SftpException e) {
e.printStackTrace();
log.error("创建目录[" + tempPath + "]失败,异常信息[" + e.getMessage() + "]");
}
log.info("进入目录[" + tempPath + "]");
mkdirDir(dirs, tempPath, length, index);
}
}/*** 将输入流的数据上传到sftp作为文件(多层目录)
*
*@paramdirectory 上传到该目录(多层目录)
*@paramsftpFileName sftp端文件名
*@paraminput 输入流
*@throwsSftpException
*@throwsException*/
public void uploadMore(String directory, String sftpFileName, InputStream input) throwsSftpException {try{
sftp.cd(directory);
}catch(SftpException e) {//目录不存在,则创建文件夹
String[] dirs = directory.split("/");
String tempPath= "";int index = 0;
mkdirDir(dirs, tempPath, dirs.length, index);
}
sftp.put(input, sftpFileName);//上传文件
}/*** 将输入流的数据上传到sftp作为文件
*
*@paramdirectory 上传到该目录(单层目录)
*@paramsftpFileName sftp端文件名
*@paraminput 输入流
*@throwsSftpException
*@throwsException*/
public void upload(String directory, String sftpFileName, InputStream input) throwsSftpException {try{
sftp.cd(directory);
}catch(SftpException e) {
log.warn("directory is not exist");
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
log.info("file:{} is upload successful", sftpFileName);
}/*** 上传单个文件
*
*@paramdirectory 上传到sftp目录
*@paramuploadFile 要上传的文件,包括路径
*@throwsFileNotFoundException
*@throwsSftpException
*@throwsException*/
public void upload(String directory, String uploadFile) throwsFileNotFoundException, SftpException {
File file= newFile(uploadFile);
upload(directory, file.getName(),newFileInputStream(file));
}/*** 将byte[]上传到sftp,作为文件。注意:从String生成byte[]是,要指定字符集。
*
*@paramdirectory 上传到sftp目录
*@paramsftpFileName 文件在sftp端的命名
*@parambyteArr 要上传的字节数组
*@throwsSftpException
*@throwsException*/
public void upload(String directory, String sftpFileName, byte[] byteArr) throwsSftpException {
upload(directory, sftpFileName,newByteArrayInputStream(byteArr));
}/*** 将字符串按照指定的字符编码上传到sftp
*
*@paramdirectory 上传到sftp目录
*@paramsftpFileName 文件在sftp端的命名
*@paramdataStr 待上传的数据
*@paramcharsetName sftp上的文件,按该字符编码保存
*@throwsUnsupportedEncodingException
*@throwsSftpException
*@throwsException*/
public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throwsUnsupportedEncodingException, SftpException {
upload(directory, sftpFileName,newByteArrayInputStream(dataStr.getBytes(charsetName)));
}/*** 下载文件
*
*@paramdirectory 下载目录
*@paramdownloadFile 下载的文件
*@paramsaveFile 存在本地的路径
*@throwsSftpException
*@throwsFileNotFoundException
*@throwsException*/
public void download(String directory, String downloadFile, String saveFile) throwsSftpException, FileNotFoundException {if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file= newFile(saveFile);
sftp.get(downloadFile,newFileOutputStream(file));
log.info("file:{} is download successful", downloadFile);
}/*** 下载文件
*
*@paramdirectory 下载目录
*@paramdownloadFile 下载的文件名
*@return字节数组
*@throwsSftpException
*@throwsIOException
*@throwsException*/
public byte[] download(String directory, String downloadFile) throwsSftpException, IOException {if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is=sftp.get(downloadFile);byte[] fileData =IOUtils.toByteArray(is);
log.info("file:{} is download successful", downloadFile);returnfileData;
}/*** 删除文件
*
*@paramdirectory 要删除文件所在目录
*@paramdeleteFile 要删除的文件
*@throwsSftpException
*@throwsException*/
public void delete(String directory, String deleteFile) throwsSftpException {
sftp.cd(directory);
sftp.rm(deleteFile);
}/*** 列出目录下的文件
*
*@paramdirectory 要列出的目录
*@return*@throwsSftpException*/
public Vector> listFiles(String directory) throwsSftpException {returnsftp.ls(directory);
}public static void main(String[] args) throwsSftpException, IOException {
SFTPUtil sftp= new SFTPUtil("root", "111111", "192.168.1.124", 22);
sftp.login();
File file= new File("C:\\Users\\saq\\Desktop\\lt\\1.txt");
InputStream is= newFileInputStream(file);//多级目录创建并上传
sftp.uploadMore("/a/b/c/d", "test_20200625.dat", is);
sftp.logout();
}
}