SftpUtils


package xxx;import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector; /**
* sftp工具类
* Created by wdj on 2017/5/26.
*  
*/
public class SftpUtils
{
private static Logger log = LoggerFactory.getLogger(SftpUtils.class); private String host;
private String username;
private String password;
private int port = 22;
private ChannelSftp sftp = null;
private Session sshSession = null; public SftpUtils()
{
} public SftpUtils(String host, int port, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
this.port = port;
} public SftpUtils(String host, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
} /**
*  * 通过SFTP连接服务器
*  
*/
public boolean connect()
{
try
{
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password); Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
if (log.isInfoEnabled())
{
log.info("jsch Session connected.");
} Channel channel = sshSession.openChannel("sftp");
channel.connect();
if (log.isInfoEnabled())
{
log.info("jsch Opening sftp Channel.");
} sftp = (ChannelSftp) channel;
if (log.isInfoEnabled())
{
log.info("Connected to " + host + ".");
} return true;
}
catch (Exception e)
{
log.error(" sftp 连接超时...{}", e.getMessage());
} return false;
} /**
*  * 关闭连接
*  
*/
public void disconnect()
{
if (this.sftp != null)
{
if (this.sftp.isConnected())
{
this.sftp.disconnect();
if (log.isInfoEnabled())
{
log.info(" sftp is closed");
}
}
}
if (this.sshSession != null)
{
if (this.sshSession.isConnected())
{
this.sshSession.disconnect();
if (log.isInfoEnabled())
{
log.info(" sshSession is closed");
}
}
}
} /**
*  * 批量下载文件
*  * @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg: /home/sftp/2014/)
*  * @param localPath:本地保存目录(以路径符号结束,D:\downloac\sftp\)
*  * @param prefix:文件名开头
*  * @param suffix:文件名结尾
*  * @param delRemote:下载后是否删除sftp文件
*  * @return
*  
*/
public List<String> downloadFiles(String remotePath, String localPath, String prefix, String suffix, boolean delRemote)
{
List<String> downfiles = new ArrayList<String>();
try
{
Vector v = listFiles(remotePath); if (v.size() > 0)
{
prefix = prefix == null ? "" : prefix.trim();
suffix = suffix == null ? "" : suffix.trim(); boolean isDown;
Iterator it = v.iterator();
while (it.hasNext())
{
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir())
{
File localFile = new File(localPath, filename);
// 验证开头和结尾
if ((prefix.equals("") || filename.startsWith(prefix)) && (suffix.equals("") || filename.endsWith(suffix)))
{
isDown = downloadFile(remotePath, filename, localFile);
if (isDown)
{
downfiles.add(localFile.getName());
if (delRemote)
deleteSFTP(remotePath, filename);
}
}
}
} if (log.isInfoEnabled())
{
log.info("file download success,file size : {}", downfiles.size());
}
}
}
catch (SftpException e)
{
e.printStackTrace();
}
finally {
// this.disconnect();
}
return downfiles;
} /**
* 下载单个文件
*
* @param remotePath
* @param remoteFileName
* @param localFile
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName, File localFile)
{
//FileOutputStream fieloutput = null;
try
{
// sftp.cd(remotePath);
// mkdirs(localPath + localFileName);
//fieloutput = new FileOutputStream(localFile); // sftp.get(remotePath + remoteFileName, fieloutput);
sftp.get(remotePath + remoteFileName, localFile.getAbsolutePath()); log.info("=== file.download: [{}] success.", remoteFileName);
return true;
}
catch (Exception e)
{
if (e.getMessage().toLowerCase().equals("no such file"))
{
if (log.isDebugEnabled())
{
log.debug("=== file.download.error: [{}], {}.", remoteFileName, e.getMessage());
}
}
else
log.error("=== file.download.error: [{}], {}.", remoteFileName, e.getMessage()); localFile.delete();
}
finally
{
// if (null != fieloutput)
// {
// try
// {
// fieloutput.close();
// }
// catch (IOException e)
// {
// }
// }
}
return false;
} /**
*  * 上传单个文件
*  * @param remotePath:远程保存目录
*  * @param remoteFileName:保存文件名
*  * @param localPath:本地上传目录(以路径符号结束)
*  * @param localFileName:上传的文件名
*  * @return
*  
*/
public boolean uploadFile(String remotePath, String remoteFileName, String localFile)
{
FileInputStream in = null;
try
{
cdDir(remotePath);
in = new FileInputStream(localFile);
sftp.put(in, remoteFileName); if (log.isInfoEnabled())
{
log.info(" file.upload: [{}] success.", localFile.substring(localFile.lastIndexOf(File.separator)));
} 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 remotePath:远程保存目录
*  * @param localPath:本地上传目录(以路径符号结束)
*  * @param delLocal:上传后是否删除本地文件
*  * @return
*  
*/
public List<String> uploadFiles(String remotePath, String localPath, String prefix, String suffix, boolean delLocal)
{
List<String> upfiles = new ArrayList<String>();
try
{
File file = new File(localPath);
File[] files = file.listFiles(); prefix = prefix == null ? "" : prefix.trim();
suffix = suffix == null ? "" : suffix.trim(); for (int i = 0; i < files.length; i++)
{
String fileName = files[i].getName();
if ((prefix.equals("") || fileName.startsWith(prefix)) && (suffix.equals("") || fileName.endsWith(suffix)))
{
if (files[i].isFile())
{
boolean isUpload = this.uploadFile(remotePath, fileName, files[i].getAbsolutePath());
if (isUpload)
{
upfiles.add(files[i].getAbsolutePath());
if (delLocal)
deleteLocal(files[i]);
}
}
}
} if (log.isInfoEnabled())
{
log.info(" file upload success,file size : {}", upfiles.size());
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
this.disconnect();
} return upfiles; } /**
*  * 删除本地文件
*  * @param filePath
*  * @return
*  
*/
public boolean deleteLocal(File file)
{
if (!file.exists())
{
return false;
} if (!file.isFile())
{
return false;
} boolean rs = file.delete();
if (rs && log.isInfoEnabled())
{
log.info(" file.delete.success.");
}
return rs;
} /**
*  * 创建目录
*  * @param createpath
*  * @return
*  
*/
public boolean cdDir(String createpath)
{
try
{ String pwd = this.sftp.pwd();
if (pwd.contains("/" + createpath + "/"))
return true; if (isDirExist(createpath))
{
this.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());
} } pwd = this.sftp.pwd();
if (pwd.contains("/" + createpath + "/"))
return true;
}
catch (SftpException e)
{
e.printStackTrace();
}
return false;
} /**
*  * 判断目录是否存在
*  * @param directory
*  * @return
*  
*/
public boolean isDirExist(String directory)
{
boolean isDirExistFlag = false;
try
{
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
}
catch (SftpException e)
{
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
//if (e.getMessage().toLowerCase().equals("no such file"))
{
isDirExistFlag = false;
}
}
return isDirExistFlag;
} /**
*  * 删除stfp文件
*  * @param directory:要删除文件所在目录
*  * @param deleteLocal:要删除的文件
*  * @param sftp
*  
*/
public void deleteSFTP(String directory, String deleteFile)
{
try
{
// sftp.cd(directory);
sftp.rm(directory + deleteFile);
if (log.isInfoEnabled())
{
log.info("delete file success from sftp.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
} /**
*  * 如果目录不存在就创建目录
*  * @param path
*  
*/
public void mkdirs(String path)
{
File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists())
{
f.mkdirs();
}
} /**
*  * 列出目录下的文件
*  *
*  * @param directory:要列出的目录
*  * @param sftp
*  * @return
*  * @throws SftpException
*  
*/
public Vector listFiles(String directory) throws SftpException
{
return sftp.ls(directory);
} public String getHost()
{
return host;
} public void setHost(String host)
{
this.host = host;
} public String getUsername()
{
return username;
} public void setUsername(String username)
{
this.username = username;
} public String getPassword()
{
return password;
} public void setPassword(String password)
{
this.password = password;
} public int getPort()
{
return port;
} public void setPort(int port)
{
this.port = port;
} public ChannelSftp getSftp()
{
return sftp;
} public void setSftp(ChannelSftp sftp)
{
this.sftp = sftp;
} /**
* 测试
*/
public static void main(String[] args)
{ // SftpUtils sftp = null;
// // 本地存放地址
// String localPath = "D:\\dev\\java\\workspace\\testobj\\outfiles\\";
//
// // Sftp下载路径
// String sftpPath = "/home/web/static/js/";
// List<String> filePathList = new ArrayList<String>();
// try
// {
// sftp = new SftpUtils("127.0.0.1", 22, "root", "xxxx");
// sftp.connect();
// // 下载
// // sftp.downloadFiles(sftpPath, localPath, "", ".js", false);
//
// sftp.uploadFiles(sftpPath, localPath, "", "rar", true);
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// sftp.disconnect();
// }
}
}

JAVA Sftp 上传下载的更多相关文章

  1. Java Sftp上传下载文件

    需要使用jar包  jsch-0.1.50.jar sftp上传下载实现类 package com.bstek.transit.sftp; import java.io.File; import ja ...

  2. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  3. Java SFTP 上传、下载等操作

    Java SFTP 上传.下载等操作 实际开发中用到了 SFTP 用于交换批量数据文件,然后琢磨了下这方面的东西,基于 JSch 写了个工具类记录下,便于日后使用. JSch是 SSH2 的纯Java ...

  4. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  5. THINKPHP 3.2 PHP SFTP上传下载 代码实现方法

     一.SFTP介绍:使用SSH协议进行FTP传输的协议叫SFTP(安全文件传输)Sftp和Ftp都是文件传输协议.区别:sftp是ssh内含的协议(ssh是加密的telnet协议),  只要sshd服 ...

  6. Xshell5下利用sftp上传下载传输文件

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH ...

  7. SFTP上传下载文件、文件夹常用操作

    SFTP上传下载文件.文件夹常用操作 1.查看上传下载目录lpwd 2.改变上传和下载的目录(例如D盘):lcd  d:/ 3.查看当前路径pwd 4.下载文件(例如我要将服务器上tomcat的日志文 ...

  8. java 实现Serv-U FTP 和 SFTP 上传 下载

    两种ftp使用java的实现方式 ,代码都已测试 第一种:Serv-U FTP 先决条件: 1.Serv-U FTP服务器搭建成功. 2.jar包需要:版本不限制 <!--ftp上传需要的jar ...

  9. java之SFTP上传下载

    import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.ut ...

随机推荐

  1. TCP/IP四层模型和OSI七层模型(模型分层的作用是什么)

    TCP/IP四层模型和OSI七层模型的概念(模型分层的作用是什么) 一.总结 一句话总结: 减轻问题的复杂程度,一旦网络发生故障,可迅速定位故障所处层次,便于查找和纠错: 在各层分别定义标准接口,使具 ...

  2. Java笔记 - 异常机制

    JAVA异常机制是Java提供的用于处理程序在运行期可能出现的异常事件(如数组下标越界.文件不存在等)的一种机制,使程序不会因为 异常的发生 而 阻断或产生不可预见的结果 .而且还可以将逻辑代码与错误 ...

  3. 实例测试java的Integer转String的效率问题1.8

    原文链接:https://blog.csdn.net/chicaohun7473/article/details/100851373 查看String源码时,读到源码的toString方法时,打算探究 ...

  4. 11-6-es5选项卡

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. Luogu P4782 【模板】2-SAT 问题(2-SAT)

    P4782 [模板]2-SAT 问题 题意 题目背景 \(2-SAT\)问题模板 题目描述 有\(n\)个布尔变量\(x_1\sim x_n\),另有\(m\)个需要满足的条件,每个条件的形式都是&q ...

  6. csp-s模拟测试52平均数,序列题解

    题面:https://www.cnblogs.com/Juve/articles/11602244.html 平均数: 第k个平均数不好求,我们考虑二分,转化成平均数小于x的有几个 虑把序列中的每个数 ...

  7. NMS 和 Soft-NMS

    转自https://zhuanlan.zhihu.com/p/42018282 一 NMS NMS算法的大致思想:对于有重叠的候选框:若大于规定阈值(某一提前设定的置信度)则删除,低于阈值的保留.对于 ...

  8. 63 搜索旋转排序数组II

    原题网址:https://www.lintcode.com/problem/search-in-rotated-sorted-array-ii/description 描述 跟进“搜索旋转排序数组”, ...

  9. Django项目: 项目环境搭建 ---- 一、创建django项目

    项目环境搭建 一.创建django项目 1.创建python虚拟环境 在虚拟机上创建python虚拟环境,因为实际项目部署,实在linux mkvirtualenv -p /usr/bin/pytho ...

  10. Linux时间介绍

    Linux时钟分为系统时钟(System Clock)和硬件(Real Time Clock,简称RTC)时钟.系统时钟是指当前Linux Kernel中的时钟,而硬件时钟则是主板上由电池供电的时钟, ...