欢迎访问个人博客 德鲁大叔撸代码
SFTP工具类:
/**
* @ClassName SftpUtils
* @Description sftp工具类
* @Author tengxiao.ma
* @Date 2020/3/20 11:08
**/
@Component
@Slf4j
public class SftpUtils {
private static ChannelSftp sftp = null;
private static Session sshSession = null;
}
具体的方法如下:
一 :连接SFTP服务器方法
public ChannelSftp connect() {
String sftpPwd = PyxisConfig.getInstance().getProperty(Constants.SFTP_PWD); //密码
String sftpHost = PyxisConfig.getInstance().getProperty(Constants.SFTP_HOST); //ip
int port = Integer.valueOf(PyxisConfig.getInstance().getProperty(Constants.SFTP_PORT)); //端口号
String sftpUser = PyxisConfig.getInstance().getProperty(Constants.SFTP_USER); //用户名
try {
JSch jsch = new JSch();
jsch.getSession(sftpUser, sftpHost, port);
sshSession = jsch.getSession(sftpUser, sftpHost, port);
sshSession.setPassword(sftpPwd);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(30000);
Channel channel = sshSession.openChannel("sftp");
channel.connect(10000);
sftp = (ChannelSftp) channel;
log.info("连接SFTP服务器{}成功",sftpHost);
return sftp;
} catch (Exception e) {
log.info("连接SFTP服务器{}失败,对账异常结束{}",sftpHost,e);
return null;
}
}
二:一些公共的方法
1 判断文件夹是否存在
public static boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
//lstat()检索文件或目录的文件属性
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
//isDir()检查此文件是否为目录
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
2 创建目录
public static boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
3 删除文件
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
return rs;
}
4 关闭sftp连接
public static void disconnect() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
}
5 删除stfp文件
/**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
*/
public static void deleteSFTP(String directory, String deleteFile) {
try {
sftp.rm(directory + deleteFile);
} catch (Exception e) {
log.info("删除SFTP文件失败");
}
}
三、单个文件上传
/**
* 上传单个文件
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
public static boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName){
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (SftpException e){
e.printStackTrace();
}
finally
{
if (in != null){
try{
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return false;
}
四、单个文件下载
/**
* 下载单个文件
* @param directory 下载目录(远程文件所在目录)
* @param downloadFile 下载的文件名
* @param saveFile 结束文件的全路径
* @param sftp
*/
public static void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.get(downloadFile,saveFile);
}catch (Exception e){
log.info("下载sftp文件失败");
}
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public static boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
File file = new File(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
五、批量上传文件
/**
* 批量上传文件
* @param remotePath 远程地址
* @param localPath 本地文件路径
* @param del
* @return
*/
public static boolean bacthUploadFile(String remotePath, String localPath,boolean del) {
try {
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1) {
if (uploadFile(remotePath, files[i].getName(),localPath, files[i].getName())&& del) {
//上传后删除本地文件
deleteFile(localPath + files[i].getName());
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
return false;
}
六、批量文件下载
/**
* 批量下载文件
* @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
public static List<String> batchDownLoadFile(String remotePath, String localPath,String fileFormat, String fileEndFormat, boolean del) {
List<String> filenames = new ArrayList<String>();
try {
Vector v = sftp.ls(remotePath); //lstat(String path):列出远程目录的内容
if (v.size() > 0) {
System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
Iterator it = v.iterator();
while (it.hasNext()) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
} catch (SftpException e) {
e.printStackTrace();
} finally {
}
return filenames;
}