首先,需要在pom文件中引入链接sftp的依赖,我这里用的是jsch,如下:

<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency>

其次,建立sftp链接工具类:

package com.apache.https.sinosoft.common;import com.jcraft.jsch.*;import java.io.*;
import java.util.*;public class FTPUtils {/*** sftp工具类**/private ChannelSftp sftp = null;private Session sshSession = null;/*** 通过SFTP连接服务器*/public void connect(String ip,String port,String userName,String password){try{System.out.println("sft链接开始---》connect---begin");int sftpPort = 22;//端口号if(null != port && !"".equals(port)){sftpPort = Integer.valueOf(port);}JSch jsch = new JSch();jsch.getSession(userName, ip, sftpPort);sshSession = jsch.getSession(userName, ip, sftpPort);System.out.println("ip="+ip+"--->port"+port);sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);// 登录sshSession.connect();System.out.println("sftp链接成功------>success");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;System.out.println("sft链接结束---》connect---end");}catch (Exception e){e.printStackTrace();}}/*** 关闭连接*/public void disconnect() {System.out.println("sft关闭链接开始---》disconnect---begin");if (this.sftp != null) {if (this.sftp.isConnected()) {this.sftp.disconnect();}}if (this.sshSession != null) {if (this.sshSession.isConnected()) {this.sshSession.disconnect();}}System.out.println("sft关闭链接结束---》disconnect---end");}/*** 批量下载文件** @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)* @param fileEndFormat:下载文件格式(文件格式)* @param del:下载后是否删除sftp文件* @return*/public List<String> batchDownLoadFile(String remotePath, String localPath,String fileFormat, String fileEndFormat, boolean del) {List<String> filenames = new ArrayList<String>();try {// connect();Vector v = listFiles(remotePath);// sftp.cd(remotePath);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 {// this.disconnect();}return filenames;}/*** 下载单个文件** @param ftpPath:远程下载目录(以路径符号结束)* @param remoteFileName:下载文件名* @param localPath:本地保存目录(以路径符号结束)* @param localFileName:保存文件名* @return*/public boolean downloadFile(String ftpPath, String remoteFileName, String localPath, String localFileName) {FileOutputStream fieloutput = null;System.out.println("sftp下载文件开始----->downLoad---begin");try {System.out.println("本地文件路径名称"+localPath + localFileName);File file1 = new File(localPath);if(!file1.exists()){file1.mkdirs();}File file = new File(localPath + localFileName);fieloutput = new FileOutputStream(file);System.out.println("服务器文件路径名称"+ftpPath + remoteFileName);sftp.get(ftpPath + remoteFileName, fieloutput);System.out.println("sftp下载文件结束----->downLoad---end");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 remoteFileName:保存文件名* @param localPath:本地上传目录(以路径符号结束)* @param localFileName:上传的文件名* @return*/public 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 remotePath:远程保存目录* @param localPath:本地上传目录(以路径符号结束)* @param del:上传后是否删除本地文件* @return*/public 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 (this.uploadFile(remotePath, files[i].getName(),localPath, files[i].getName())    && del) {deleteFile(localPath + files[i].getName());}}}return true;} catch (Exception e) {e.printStackTrace();} finally {this.disconnect();}return false;}/*** 删除本地文件** @param filePath* @return*/public 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;}/*** 创建目录** @param createpath* @return*/public boolean createDir(String createpath) {try {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());}}this.sftp.cd(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 (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isDirExistFlag = false;}}return isDirExistFlag;}/*** 删除stfp文件** @param directory:要删除文件所在目录* @param deleteFile:要删除的文件*/public void deleteSFTP(String directory, String deleteFile) {try {// sftp.cd(directory);sftp.rm(directory + deleteFile);} 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:要列出的目录* @return* @throws SftpException*/public Vector listFiles(String directory) throws SftpException {return sftp.ls(directory);}/*** 测试*/public static void main(String[] args) {FTPUtils sftp = null;// 本地存放地址String localPath = "D:/tomcat5/webapps/ASSESS/DocumentsDir/DocumentTempDir/txtData/";// Sftp下载路径String sftpPath = "/home/assess/sftp/jiesuan_2/2014/";List<String> filePathList = new ArrayList<String>();try {
//          sftp = new FTPUtils("10.163.201.115", "tdcp", "tdcp");sftp.connect("10.163.201.115", "21", "tdcp","tdcp");// 下载sftp.batchDownLoadFile(sftpPath, localPath, "ASSESS", ".txt", true);} catch (Exception e) {e.printStackTrace();} finally {sftp.disconnect();}}
}

这里我用的是批量文件下载,代码如下:

String date = request.getParameter("date");String ftpIP = SysConfig.getPropertity("ZBFFTPIP"); // ipString ftpPort = SysConfig.getPropertity("ZBFFTPPORT"); // port端口String ftpUserName = SysConfig.getPropertity("ZBFFTPUSERNAME"); // 用户名String ftpPassWord = SysConfig.getPropertity("ZBFFTPPASSWORD"); // 密码String ftpPath = SysConfig.getPropertity("ZBFFTPPATH");// ftp路径String localFilePath = SysConfig.getPropertity("RECONCILIATIONFILEPATH"); // 本地路径// 从sftp下载路径String path = ftpPath;FTPUtils sftp = new FTPUtils();try {// 链接sftp进行对账文件下载sftp.connect(ftpIP,ftpPort,ftpUserName,ftpPassWord);List<String> strings = sftp.batchDownLoadFile(path+date+"/", localFilePath+date+"/", "", ".txt", false);} catch (Exception e) {e.printStackTrace();} finally {sftp.disconnect();response.flushBuffer();}

工具类中也有其他的方法可以调用,大家可以试一下。

实现sftp链接,并下载服务器上文件相关推荐

  1. WebRequest之HttpWebRequest实现服务器上文件的下载(一)

    WebRequest是操作WEB请求的抽象象,它作为所有WEB请求的基类,主要由FileWebRequest.FtpWebRequest.HttpWebRequest这三个类进行实现.(选自MSDN) ...

  2. js 下载服务器上的文件

    今天用js下载服务器上的文件txt时,文件总是被打开,而不是下载. 解决方法: 直接下载txt文件是实现不了的,将txt文件压缩成rar格式,这样再去下载就没有问题了.(这也是为什么很多下载的文件都为 ...

  3. java拷贝远程服务器上文件,java拷贝远程服务器上文件

    java拷贝远程服务器上文件 内容精选 换一换 在Windows模式下,调试功能暂不可用.为支持多交叉架构的调试场景,需要在安装MindStudio的服务器(UI Host)上安装gdb-multia ...

  4. java 跨服务器 文件拷贝,java拷贝远程服务器上文件

    java拷贝远程服务器上文件 内容精选 换一换 已成功登录Java性能分析.待安装Guardian的服务器已开启sshd.待安装Guardian的服务器已安装JRE,JRE版本要求为Huawei JD ...

  5. scp 服务器文件到本地,scp将远程服务器上文件拷贝到本地

    scp将远程服务器上文件拷贝到本地 内容精选 换一换 目前开发的新项目使用的版本控制工具基本用的都是Git,老项目用的还是Svn,网上Git资源也很多,多而杂.一. Git 命令初识在正式介绍Git命 ...

  6. java获取服务器上指定文件,java 读取服务器上文件

    java 读取服务器上文件 [2021-02-04 10:02:14]  简介: php去除nbsp的方法:首先创建一个PHP代码示例文件:然后通过"preg_replace("/ ...

  7. 服务器上复制文件到本地会有什么,scp将远程服务器上文件拷贝到本地

    scp将远程服务器上文件拷贝到本地 内容精选 换一换 1.openssh简介:用于远程连接服务器主机,通信过程和认证过程都是加密的,比telnet更安全.2.openssh版本:v1版本:无法防范中间 ...

  8. 【Linux】上传和下载服务器上的文件

    (1) Xshell: Xshell 只能通过 "sz 文件名" 和 "rz" 来下载和上传文件,也可以直接通过将电脑上的文件拖动到Xshell窗口的方式来上传 ...

  9. JAVA实现FTP服务器上文件上传下载以及文件在线预览

    (一)介绍文件上传下载: (1)前端思路: 用formData封装好file以及相关参数,然后l利用ajax请求往后台传数据 html的代码:<input id="cm_file&qu ...

最新文章

  1. OutOfMemoryError/OOM/内存溢出异常实例分析--堆内存溢出
  2. pytorch基础操作学习笔记(autograd,Tensor)
  3. c++图书管理系统_轻松学做C语言课程设计:图书管理系统-数组实现
  4. 面试必问:如何访问 Redis 中的海量数据?
  5. TP框架对数据库的基本操作
  6. excel中,0不显示,负数显示红色
  7. JavaSE学习--正则表达式
  8. 软件工程 -- 用例图
  9. 《结构分析的有限元法与MATLAB程序设计》笔记
  10. demo:用matlab app designer做一个简易app
  11. 177.5. FAQ
  12. tagged和untagged
  13. 基于AKF可扩展模型的微服务拆分方式
  14. 当php懈垢windows通用上传缺陷
  15. python3---字符串
  16. P1969 [NOIP2013 提高组] 积木大赛(差分+贪心)
  17. 关于CTF压缩包的那些事
  18. 【Guacamole中文文档】二、用户指南—— 2.Guacamole源码安装
  19. 出行必备降噪耳机哪款好?南卡、华为降噪耳机对比测评
  20. 设置 按下电源按钮时锁定计算机,在这里设置在按下计算机电源按钮时下拉菜单...

热门文章

  1. 永远怀念Steve Jobs——时代的先驱者
  2. 全国计算机四级薪资,全国计算机四级考试之心得
  3. 安装包UI美化之路-nsNiuniuSkin安装包模板介绍
  4. 同步DC-DC降压型LED驱动IC
  5. WordPress-Light Year简洁小清新风格网站主题
  6. 使用RenderScript-v8 报错的问题 couldn't find librsjni.so
  7. 抢注商标是蹭热点还是“不要脸”?
  8. SAP adobe form step by step 视频学习教程
  9. linux中expr的用法,linux expr命令参数及用法详解(示例代码)
  10. OpenCV-图像旋转Rotate