作者在 2022-03-09 15:07:19 发布以下内容
用到的jar包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
封装工具类
package com.cn.util;
import com.cn.wisdom.common.RestControllerException;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
@Slf4j
public class SFTPUtils {
private static final Logger LOG = LoggerFactory.getLogger(SFTPUtils.class);
private SFTPUtils() {
}
/**
* 连接sftp服务器
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
LOG.info("SFTP Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
LOG.info("Connected to " + host);
} catch (Exception e) {
LOG.error(e.getMessage());
}
return sftp;
}
/**
* 上传文件
*
* @param directory 上传的目录
* @param importFile 要上传的文件
*/
public static boolean upload(String directory, MultipartFile importFile, String username, String password, String host, int port) {
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
LOG.info("SFTP Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
createDir(directory, sftp);
InputStream is = importFile.getInputStream();
sftp.put(is, importFile.getOriginalFilename());
return true;
} catch (Exception e) {
LOG.error(e.getMessage());
return false;
}
}
public static void createDir(String createpath, ChannelSftp sftp) {
try {
if (isDirExist(createpath,sftp)) {
sftp.cd(createpath);
return;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString(),sftp)) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
sftp.cd(createpath);
} catch (SftpException e) {
throw new RestControllerException("创建路径错误:" + createpath);
}
}
/**
* 判断目录是否存在
*/
public static boolean isDirExist(String directory,ChannelSftp sftp) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
*/
public File download(String directory, String downloadFile, String saveFile,ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFile, fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
LOG.error(e.getMessage());
return null;
}
}
/**
* 下载文件
*
* @param downloadFilePath 下载的文件完整目录
* @param saveFile 存在本地的路径
*/
public File download(String downloadFilePath, String saveFile,ChannelSftp sftp) {
try {
int i = downloadFilePath.lastIndexOf('/');
if (i == -1)
return null;
sftp.cd(downloadFilePath.substring(0, i));
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
LOG.error(e.getMessage());
return null;
}
}
/**
* 删除文件
*
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
*/
public void delete(String directory, String deleteFile,ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
public void disconnect(ChannelSftp sftp) {
try {
sftp.getSession().disconnect();
} catch (JSchException e) {
LOG.error(e.getMessage());
}
sftp.quit();
sftp.disconnect();
}
/**
* 列出目录下的文件
*
* @param directory 要列出的目录
* @throws SftpException
*/
public Vector<LsEntry> listFiles(String directory,ChannelSftp sftp) throws SftpException {
return sftp.ls(directory);
}
}
调用发放
//ftpBasePath 是ftp的服务器目录;
//ftpName 用户名
//ftpPassword 密码
//ftpIp 地址
SFTPUtils.upload(ftpBasePath + basePath,importFile,ftpName,ftpPassword,ftpIp,22);