Sftp工具类(转)

1,添加Maven依赖

1         <dependency>
2             <groupId>jsch</groupId>
3             <artifactId>jsch</artifactId>
4             <version>0.1.29</version>
5         </dependency>

2,构造方法摘要

 1     /**
 2      * SFTP 安全文件传送协议
 3      *
 4      * @param host     SFTP服务器IP地址
 5      * @param port     SFTP服务器端口
 6      * @param timeout  连接超时时间,单位毫秒
 7      * @param username 用户名
 8      * @param password 密码
 9      */
10     public SftpUtil(String host, int port, int timeout, String username, String password)
11     {
12         this.host = host;
13         this.port = port;
14         this.timeout = timeout;
15         this.username = username;
16         this.password = password;
17     }

3,封装API说明

4,源代码

  1 import com.jcraft.jsch.*;
  2 import com.jcraft.jsch.ChannelSftp.LsEntry;
  3 import org.slf4j.Logger;
  4 import org.slf4j.LoggerFactory;
  5 
  6 import java.io.File;
  7 import java.io.InputStream;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 import java.util.Properties;
 11 import java.util.Vector;
 12 
 13 /**
 14  * Created by xiaokang
 15  * Date:2018/6/28
 16  * Time:15:02
 17  */
 18 public class SftpUtil
 19 {
 20     private Logger logger = LoggerFactory.getLogger(SftpUtil.class);
 21 
 22     /**
 23      * Session
 24      */
 25     private Session session = null;
 26     /**
 27      * Channel
 28      */
 29     private ChannelSftp channel = null;
 30     /**
 31      * SFTP服务器IP地址
 32      */
 33     private String host;
 34     /**
 35      * SFTP服务器端口
 36      */
 37     private int port;
 38     /**
 39      * 连接超时时间,单位毫秒
 40      */
 41     private int timeout;
 42 
 43     /**
 44      * 用户名
 45      */
 46     private String username;
 47     /**
 48      * 密码
 49      */
 50     private String password;
 51 
 52     /**
 53      * SFTP 安全文件传送协议
 54      *
 55      * @param host     SFTP服务器IP地址
 56      * @param port     SFTP服务器端口
 57      * @param timeout  连接超时时间,单位毫秒
 58      * @param username 用户名
 59      * @param password 密码
 60      */
 61     public SftpUtil(String host, int port, int timeout, String username, String password)
 62     {
 63         this.host = host;
 64         this.port = port;
 65         this.timeout = timeout;
 66         this.username = username;
 67         this.password = password;
 68     }
 69 
 70     /**
 71      * 登陆SFTP服务器
 72      *
 73      * @return boolean
 74      */
 75     public boolean login()
 76     {
 77 
 78         try {
 79             JSch jsch = new JSch();
 80             session = jsch.getSession(username, host, port);
 81             if (password != null) {
 82                 session.setPassword(password);
 83             }
 84             Properties config = new Properties();
 85             config.put("StrictHostKeyChecking", "no");
 86             session.setConfig(config);
 87             session.setTimeout(timeout);
 88             session.connect();
 89             logger.debug("sftp session connected");
 90 
 91             logger.debug("opening channel");
 92             channel = (ChannelSftp) session.openChannel("sftp");
 93             channel.connect();
 94 
 95             logger.debug("connected successfully");
 96             return true;
 97         } catch (JSchException e) {
 98             logger.error("sftp login failed", e);
 99             return false;
100         }
101     }
102 
103     /**
104      * 上传文件
105      *
106      * @param pathName SFTP服务器目录
107      * @param fileName 服务器上保存的文件名
108      * @param input    输入文件流
109      * @return boolean
110      */
111     public boolean uploadFile(String pathName, String fileName, InputStream input)
112     {
113 
114         String currentDir = currentDir();
115         if (!changeDir(pathName)) {
116             return false;
117         }
118 
119         try {
120             channel.put(input, fileName, ChannelSftp.OVERWRITE);
121             if (!existFile(fileName)) {
122                 logger.debug("upload failed");
123                 return false;
124             }
125             logger.debug("upload successful");
126             return true;
127         } catch (SftpException e) {
128             logger.error("upload failed", e);
129             return false;
130         } finally {
131             changeDir(currentDir);
132         }
133     }
134 
135     /**
136      * 上传文件
137      *
138      * @param pathName  SFTP服务器目录
139      * @param fileName  服务器上保存的文件名
140      * @param localFile 本地文件
141      * @return boolean
142      */
143     public boolean uploadFile(String pathName, String fileName, String localFile)
144     {
145 
146         String currentDir = currentDir();
147         if (!changeDir(pathName)) {
148             return false;
149         }
150 
151         try {
152             channel.put(localFile, fileName, ChannelSftp.OVERWRITE);
153             if (!existFile(fileName)) {
154                 logger.debug("upload failed");
155                 return false;
156             }
157             logger.debug("upload successful");
158             return true;
159         } catch (SftpException e) {
160             logger.error("upload failed", e);
161             return false;
162         } finally {
163             changeDir(currentDir);
164         }
165     }
166 
167     /**
168      * 下载文件
169      *
170      * @param remotePath SFTP服务器目录
171      * @param fileName   服务器上需要下载的文件名
172      * @param localPath  本地保存路径
173      * @return boolean
174      */
175     public boolean downloadFile(String remotePath, String fileName, String localPath)
176     {
177 
178         String currentDir = currentDir();
179         if (!changeDir(remotePath)) {
180             return false;
181         }
182 
183         try {
184             String localFilePath = localPath + File.separator + fileName;
185             channel.get(fileName, localFilePath);
186 
187             File localFile = new File(localFilePath);
188             if (!localFile.exists()) {
189                 logger.debug("download file failed");
190                 return false;
191             }
192             logger.debug("download successful");
193             return true;
194         } catch (SftpException e) {
195             logger.error("download file failed", e);
196             return false;
197         } finally {
198             changeDir(currentDir);
199         }
200     }
201 
202     /**
203      * 切换工作目录
204      *
205      * @param pathName 路径
206      * @return boolean
207      */
208     public boolean changeDir(String pathName)
209     {
210         if (pathName == null || pathName.trim().equals("")) {
211             logger.debug("invalid pathName");
212             return false;
213         }
214 
215         try {
216             channel.cd(pathName.replaceAll("\\\\", "/"));
217             logger.debug("directory successfully changed,current dir=" + channel.pwd());
218             return true;
219         } catch (SftpException e) {
220             logger.error("failed to change directory", e);
221             return false;
222         }
223     }
224 
225     /**
226      * 切换到上一级目录
227      *
228      * @return boolean
229      */
230     public boolean changeToParentDir()
231     {
232         return changeDir("..");
233     }
234 
235     /**
236      * 切换到根目录
237      *
238      * @return boolean
239      */
240     public boolean changeToHomeDir()
241     {
242         String homeDir = null;
243         try {
244             homeDir = channel.getHome();
245         } catch (Exception e) {
246             logger.error("can not get home directory", e);
247             return false;
248         }
249         return changeDir(homeDir);
250     }
251 
252     /**
253      * 创建目录
254      *
255      * @param dirName 目录
256      * @return boolean
257      */
258     public boolean makeDir(String dirName)
259     {
260         try {
261             channel.mkdir(dirName);
262             logger.debug("directory successfully created,dir=" + dirName);
263             return true;
264         } catch (SftpException e) {
265             logger.error("failed to create directory", e);
266             return false;
267         }
268     }
269 
270     /**
271      * 删除文件夹
272      *
273      * @param dirName
274      * @return boolean
275      */
276     @SuppressWarnings("unchecked")
277     public boolean delDir(String dirName)
278     {
279         if (!changeDir(dirName)) {
280             return false;
281         }
282 
283         Vector<LsEntry> list = null;
284         try {
285             list = channel.ls(channel.pwd());
286         } catch (SftpException e) {
287             logger.error("can not list directory", e);
288             return false;
289         }
290 
291         for (LsEntry entry : list) {
292             String fileName = entry.getFilename();
293             if (!fileName.equals(".") && !fileName.equals("..")) {
294                 if (entry.getAttrs().isDir()) {
295                     delDir(fileName);
296                 } else {
297                     delFile(fileName);
298                 }
299             }
300         }
301 
302         if (!changeToParentDir()) {
303             return false;
304         }
305 
306         try {
307             channel.rmdir(dirName);
308             logger.debug("directory " + dirName + " successfully deleted");
309             return true;
310         } catch (SftpException e) {
311             logger.error("failed to delete directory " + dirName, e);
312             return false;
313         }
314     }
315 
316     /**
317      * 删除文件
318      *
319      * @param fileName 文件名
320      * @return boolean
321      */
322     public boolean delFile(String fileName)
323     {
324         if (fileName == null || fileName.trim().equals("")) {
325             logger.debug("invalid filename");
326             return false;
327         }
328 
329         try {
330             channel.rm(fileName);
331             logger.debug("file " + fileName + " successfully deleted");
332             return true;
333         } catch (SftpException e) {
334             logger.error("failed to delete file " + fileName, e);
335             return false;
336         }
337     }
338 
339     /**
340      * 当前目录下文件及文件夹名称列表
341      *
342      * @return String[]
343      */
344     public String[] ls()
345     {
346         return list(Filter.ALL);
347     }
348 
349     /**
350      * 指定目录下文件及文件夹名称列表
351      *
352      * @return String[]
353      */
354     public String[] ls(String pathName)
355     {
356         String currentDir = currentDir();
357         if (!changeDir(pathName)) {
358             return new String[0];
359         }
360         ;
361         String[] result = list(Filter.ALL);
362         if (!changeDir(currentDir)) {
363             return new String[0];
364         }
365         return result;
366     }
367 
368     /**
369      * 当前目录下文件名称列表
370      *
371      * @return String[]
372      */
373     public String[] lsFiles()
374     {
375         return list(Filter.FILE);
376     }
377 
378     /**
379      * 指定目录下文件名称列表
380      *
381      * @return String[]
382      */
383     public String[] lsFiles(String pathName)
384     {
385         String currentDir = currentDir();
386         if (!changeDir(pathName)) {
387             return new String[0];
388         }
389         ;
390         String[] result = list(Filter.FILE);
391         if (!changeDir(currentDir)) {
392             return new String[0];
393         }
394         return result;
395     }
396 
397     /**
398      * 当前目录下文件夹名称列表
399      *
400      * @return String[]
401      */
402     public String[] lsDirs()
403     {
404         return list(Filter.DIR);
405     }
406 
407     /**
408      * 指定目录下文件夹名称列表
409      *
410      * @return String[]
411      */
412     public String[] lsDirs(String pathName)
413     {
414         String currentDir = currentDir();
415         if (!changeDir(pathName)) {
416             return new String[0];
417         }
418         ;
419         String[] result = list(Filter.DIR);
420         if (!changeDir(currentDir)) {
421             return new String[0];
422         }
423         return result;
424     }
425 
426     /**
427      * 当前目录是否存在文件或文件夹
428      *
429      * @param name 名称
430      * @return boolean
431      */
432     public boolean exist(String name)
433     {
434         return exist(ls(), name);
435     }
436 
437     /**
438      * 指定目录下,是否存在文件或文件夹
439      *
440      * @param path 目录
441      * @param name 名称
442      * @return boolean
443      */
444     public boolean exist(String path, String name)
445     {
446         return exist(ls(path), name);
447     }
448 
449     /**
450      * 当前目录是否存在文件
451      *
452      * @param name 文件名
453      * @return boolean
454      */
455     public boolean existFile(String name)
456     {
457         return exist(lsFiles(), name);
458     }
459 
460     /**
461      * 指定目录下,是否存在文件
462      *
463      * @param path 目录
464      * @param name 文件名
465      * @return boolean
466      */
467     public boolean existFile(String path, String name)
468     {
469         return exist(lsFiles(path), name);
470     }
471 
472     /**
473      * 当前目录是否存在文件夹
474      *
475      * @param name 文件夹名称
476      * @return boolean
477      */
478     public boolean existDir(String name)
479     {
480         return exist(lsDirs(), name);
481     }
482 
483     /**
484      * 指定目录下,是否存在文件夹
485      *
486      * @param path 目录
487      * @param name 文家夹名称
488      * @return boolean
489      */
490     public boolean existDir(String path, String name)
491     {
492         return exist(lsDirs(path), name);
493     }
494 
495     /**
496      * 当前工作目录
497      *
498      * @return String
499      */
500     public String currentDir()
501     {
502         try {
503             return channel.pwd();
504         } catch (Exception e) {
505             logger.error("failed to get current dir", e);
506             return homeDir();
507         }
508     }
509 
510     /**
511      * 登出
512      */
513     public void logout()
514     {
515         if (channel != null) {
516             channel.quit();
517             channel.disconnect();
518         }
519         if (session != null) {
520             session.disconnect();
521         }
522         logger.debug("logout successfully");
523     }
524 
525 
526     //------private method ------
527 
528     /**
529      * 枚举,用于过滤文件和文件夹
530      */
531     private enum Filter
532     {
533         /**
534          * 文件及文件夹
535          */ALL, /**
536      * 文件
537      */FILE, /**
538      * 文件夹
539      */DIR
540     }
541 
542     ;
543 
544     /**
545      * 列出当前目录下的文件及文件夹
546      *
547      * @param filter 过滤参数
548      * @return String[]
549      */
550     @SuppressWarnings("unchecked")
551     private String[] list(Filter filter)
552     {
553         Vector<LsEntry> list = null;
554         try {
555             //ls方法会返回两个特殊的目录,当前目录(.)和父目录(..)
556             list = channel.ls(channel.pwd());
557         } catch (SftpException e) {
558             logger.error("can not list directory", e);
559             return new String[0];
560         }
561 
562         List<String> resultList = new ArrayList<String>();
563         for (LsEntry entry : list) {
564             if (filter(entry, filter)) {
565                 resultList.add(entry.getFilename());
566             }
567         }
568         return resultList.toArray(new String[0]);
569     }
570 
571     /**
572      * 判断是否是否过滤条件
573      *
574      * @param entry LsEntry
575      * @param f     过滤参数
576      * @return boolean
577      */
578     private boolean filter(LsEntry entry, Filter f)
579     {
580         if (f.equals(Filter.ALL)) {
581             return !entry.getFilename().equals(".") && !entry.getFilename().equals("..");
582         } else if (f.equals(Filter.FILE)) {
583             return !entry.getFilename().equals(".") && !entry.getFilename().equals("..") && !entry.getAttrs().isDir();
584         } else if (f.equals(Filter.DIR)) {
585             return !entry.getFilename().equals(".") && !entry.getFilename().equals("..") && entry.getAttrs().isDir();
586         }
587         return false;
588     }
589 
590     /**
591      * 根目录
592      *
593      * @return String
594      */
595     private String homeDir()
596     {
597         try {
598             return channel.getHome();
599         } catch (Exception e) {
600             return "/";
601         }
602     }
603 
604     /**
605      * 判断字符串是否存在于数组中
606      *
607      * @param strArr 字符串数组
608      * @param str    字符串
609      * @return boolean
610      */
611     private boolean exist(String[] strArr, String str)
612     {
613         if (strArr == null || strArr.length == 0) {
614             return false;
615         }
616         if (str == null || str.trim().equals("")) {
617             return false;
618         }
619         for (String s : strArr) {
620             if (s.equalsIgnoreCase(str)) {
621                 return true;
622             }
623         }
624         return false;
625     }
626 }
View Code

5,测试代码

  1     @Test
  2     public void contextLoads()
  3     {
  4 //        testLogin();
  5 //        testMakeDir();
  6 //        testDelFile();
  7 //        testDelEmptyDir();
  8 //        testDir();
  9 //        testLs();
 10 //        testParamLs();
 11 //        testChangeDir();
 12 //        testExist();
 13 //        testParamExist();
 14 //        testUploadFile();
 15 //        testUploadFile2();
 16 //        testDownload();
 17     }
 18 
 19 
 20     public static void testLogin()
 21     { //OK
 22         SftpUtil sftp = getSftpUtil();
 23 
 24         sftp.login();
 25         sftp.logout();
 26     }
 27 
 28     public static void testMakeDir()
 29     { //OK
 30         SftpUtil sftp = getSftpUtil();
 31         sftp.login();
 32         sftp.makeDir("test2");
 33         sftp.changeDir("test2");
 34         sftp.makeDir("/test2/test2_1");
 35         sftp.logout();
 36     }
 37 
 38     public static void testDelFile()
 39     { //OK
 40         SftpUtil sftp = getSftpUtil();
 41         sftp.login();
 42         sftp.delFile("file1.txt");
 43         sftp.logout();
 44     }
 45 
 46     public static void testDelEmptyDir()
 47     { //OK
 48         SftpUtil sftp = getSftpUtil();
 49         sftp.login();
 50         sftp.delDir("test3");
 51         sftp.logout();
 52     }
 53 
 54     public static void testDir()
 55     { //OK
 56         SftpUtil sftp = getSftpUtil();
 57         sftp.login();
 58         sftp.delDir("test4");
 59         sftp.logout();
 60     }
 61 
 62     public static void testLs()
 63     { //OK
 64         SftpUtil sftp = getSftpUtil();
 65         sftp.login();
 66         System.out.println(Arrays.toString(sftp.ls()));
 67         System.out.println(Arrays.toString(sftp.lsFiles()));
 68         System.out.println(Arrays.toString(sftp.lsDirs()));
 69         sftp.logout();
 70     }
 71 
 72     public static void testParamLs()
 73     { //OK
 74         SftpUtil sftp = getSftpUtil();
 75         sftp.login();
 76         System.out.println(Arrays.toString(sftp.ls("test1/test4")));
 77         System.out.println(Arrays.toString(sftp.lsFiles("test1/test4")));
 78         System.out.println(Arrays.toString(sftp.lsDirs("test1/test4")));
 79         sftp.logout();
 80     }
 81 
 82     public static void testChangeDir()
 83     { //OK
 84         SftpUtil sftp = getSftpUtil();
 85         sftp.login();
 86         sftp.changeDir("test1");
 87         sftp.changeDir("/test1/test4");
 88         sftp.changeToParentDir();
 89         sftp.changeToHomeDir();
 90         sftp.logout();
 91     }
 92 
 93     public static void testExist()
 94     { //OK
 95         SftpUtil sftp = getSftpUtil();
 96         sftp.login();
 97         System.out.println(sftp.exist("2fs.docx"));
 98         System.out.println(sftp.exist("test1"));
 99         System.out.println(sftp.existDir("test2"));
100         System.out.println(sftp.existDir("2sfs.txt"));
101         System.out.println(sftp.existFile("2sfs.txt"));
102         System.out.println(sftp.existFile("test2"));
103         sftp.logout();
104     }
105 
106     public static void testParamExist()
107     { //OK
108         SftpUtil sftp = getSftpUtil();
109         sftp.login();
110         System.out.println(sftp.exist("test1", "test4"));
111         System.out.println(sftp.exist("test1", "test_bak.jpg"));
112         System.out.println(sftp.existDir("/test1", "test3"));
113         System.out.println(sftp.existDir("/test1", "test_bak.jpg"));
114         System.out.println(sftp.existFile("test1", "test_bak.jpg"));
115         System.out.println(sftp.existFile("test1", "test2"));
116         sftp.logout();
117     }
118 
119 
120     public static void testUploadFile()
121     { //OK
122         SftpUtil sftp = getSftpUtil();
123         sftp.login();
124         sftp.uploadFile("/test1/test3", "test_bak2.jpg", "D:\\test.jpg");
125         try {
126             sftp.uploadFile("/test1/test2", "test_bak3.jpg", new FileInputStream("D:\\test.jpg"));
127         } catch (FileNotFoundException e) {
128             e.printStackTrace();
129         }
130         sftp.logout();
131     }
132 
133     public static void testUploadFile2()
134     { //OK
135         SftpUtil sftp = getSftpUtil();
136         sftp.login();
137         sftp.uploadFile("test1/test3", "test_bak2.jpg", "D:\\test.jpg");
138         try {
139             sftp.uploadFile("test1/test2", "test_bak3.jpg", new FileInputStream("D:\\test.jpg"));
140         } catch (FileNotFoundException e) {
141             e.printStackTrace();
142         }
143         sftp.logout();
144     }
145 
146     public static void testDownload()
147     { //OK
148         SftpUtil sftp = getSftpUtil();
149         sftp.login();
150         sftp.downloadFile("test1/test2", "a.jar", "D:/");
151         sftp.downloadFile("test1/test2", "a.jar", "D:/");
152         sftp.logout();
153     }
154 
155     private static SftpUtil getSftpUtil()
156     {
157 
158         String host = "192.168.2.181";
159         int port = 22;
160         int timeout = 10000;
161         String username = "root";
162         String password = "123456";
163 
164         SftpUtil sftp = new SftpUtil(host, port, timeout, username, password);
165 
166         return sftp;
167     }
View Code

 

转自 http://www.cnblogs.com/dongliyang/p/4173583.html

posted @ 2018-06-28 17:01  SW_Sovereign  阅读(1859)  评论(0编辑  收藏  举报