上一篇博文:https://blog.youkuaiyun.com/qq_15903671/article/details/88681240
部署了一个linux的sftp-server。客户端工具众多且不受操作系统限制,但是想灵活的制作文件上传下载流程、定时触发、文件解析转存等操作,客户端工具就可能由于功能不够完整而使用不便了。
下面使用java语言做一个简单的sftp客户端操作工具来灵活的使用sftp。
开发环境:windows、IDEA、maven、java
一、引入maven依赖
在idea工程里找到pom.xml ,添加dependence标签
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <!-- sftp文件传输相关依赖--> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.48</version> </dependency>
使用jsch依赖。
二、网上下载个操作类源码
package sshUtils; import com.jcraft.jsch.*; import java.io.*; import java.util.*; public class SFTPUtils { //private static Logger log = Logger.getLogger(SFTPUtils.class.getName()); private String host;//服务器连接ip 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 void connect() { try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); //System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); //System.out.println("Session connected."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); //System.out.println("Opening Channel."); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + " success."); } catch (Exception e) { e.printStackTrace(); } } /** * 关闭连接 */ public void disconnect() { if (this.sftp != null) { if (this.sftp.isConnected()) { this.sftp.disconnect(); System.out.println("sftp is closed already"); } } if (this.sshSession != null) { if (this.sshSession.isConnected()) { this.sshSession.disconnect(); System.out.println("sshSession is closed already"); } } } /** * 批量下载文件 * * @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();