SFTP工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SFTP工具类相关的知识,希望对你有一定的参考价值。

需要导入jsch-0.1.52.jar

  1 import java.io.File;
  2 import java.io.FileInputStream;
  3 import java.io.FileOutputStream;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.util.ArrayList;
  7 import java.util.Iterator;
  8 import java.util.List;
  9 import java.util.Properties;
 10 import java.util.Vector;
 11 
 12 import com.jcraft.jsch.Channel;
 13 import com.jcraft.jsch.ChannelSftp;
 14 import com.jcraft.jsch.ChannelSftp.LsEntry;
 15 import com.jcraft.jsch.JSch;
 16 import com.jcraft.jsch.JSchException;
 17 import com.jcraft.jsch.Session;
 18 import com.jcraft.jsch.SftpException;
 19 
 20 /**
 21  * 提供SFTP处理文件服务
 22  * 
 23  * @author krm-hehongtao
 24  * @date 2016-02-29
 25  * 
 26  */
 27 public class SFTPUtil {
 28     private JSch jSch = null;
 29     private ChannelSftp sftp = null;// sftp主服务
 30     private Channel channel = null;
 31     private Session session = null;
 32 
 33     private String hostName = "192.168.0.177";// 远程服务器地址
 34     private int port = 22;// 端口
 35     private String userName = "weblogic";// 用户名
 36     private String password = "weblogic";// 密码
 37 
 38     public SFTPUtil(String hostName, int port, String userName, String password) {
 39         this.hostName = hostName;
 40         this.port = port;
 41         this.userName = userName;
 42         this.password = password;
 43     }
 44 
 45     /**
 46      * 连接登陆远程服务器
 47      * 
 48      * @return
 49      */
 50     public boolean connect() throws Exception {
 51         try {
 52             jSch = new JSch();
 53             session = jSch.getSession(userName, hostName, port);
 54             session.setPassword(password);
 55 
 56             session.setConfig(this.getSshConfig());
 57             session.connect();
 58 
 59             channel = session.openChannel("sftp");
 60             channel.connect();
 61 
 62             sftp = (ChannelSftp) channel;
 63             System.out.println("登陆成功:" + sftp.getServerVersion());
 64 
 65         } catch (JSchException e) {
 66             System.err.println("SSH方式连接FTP服务器时有JSchException异常!");
 67             System.err.println(e.getMessage());
 68             throw e;
 69         }
 70         return true;
 71     }
 72 
 73     /**
 74      * 关闭连接
 75      * 
 76      * @throws Exception
 77      */
 78     private void disconnect() throws Exception {
 79         try {
 80             if (sftp.isConnected()) {
 81                 sftp.disconnect();
 82             }
 83             if (channel.isConnected()) {
 84                 channel.disconnect();
 85             }
 86             if (session.isConnected()) {
 87                 session.disconnect();
 88             }
 89         } catch (Exception e) {
 90             throw e;
 91         }
 92     }
 93 
 94     /**
 95      * 获取服务配置
 96      * 
 97      * @return
 98      */
 99     private Properties getSshConfig() throws Exception {
100         Properties sshConfig = null;
101         try {
102             sshConfig = new Properties();
103             sshConfig.put("StrictHostKeyChecking", "no");
104 
105         } catch (Exception e) {
106             throw e;
107         }
108         return sshConfig;
109     }
110 
111     /**
112      * 下载远程sftp服务器文件
113      * 
114      * @param remotePath
115      * @param remoteFilename
116      * @param localFilename
117      * @return
118      */
119     public boolean downloadFile(String remotePath, String remoteFilename, String localFilename)
120             throws SftpException, IOException, Exception {
121         FileOutputStream output = null;
122         boolean success = false;
123         try {
124             if (null != remotePath && remotePath.trim() != "") {
125                 sftp.cd(remotePath);
126             }
127 
128             File localFile = new File(localFilename);
129             // 有文件和下载文件重名
130             if (localFile.exists()) {
131                 System.err.println("文件: " + localFilename + " 已经存在!");
132                 return success;
133             }
134             output = new FileOutputStream(localFile);
135             sftp.get(remoteFilename, output);
136             success = true;
137             System.out.println("成功接收文件,本地路径:" + localFilename);
138         } catch (SftpException e) {
139             System.err.println("接收文件时有SftpException异常!");
140             System.err.println(e.getMessage());
141             return success;
142         } catch (IOException e) {
143             System.err.println("接收文件时有I/O异常!");
144             System.err.println(e.getMessage());
145             return success;
146         } finally {
147             try {
148                 if (null != output) {
149                     output.close();
150                 }
151                 // 关闭连接
152                 disconnect();
153             } catch (IOException e) {
154                 System.err.println("关闭文件时出错!");
155                 System.err.println(e.getMessage());
156             }
157         }
158         return success;
159     }
160 
161     /**
162      * 上传文件至远程sftp服务器
163      * 
164      * @param remotePath
165      * @param remoteFilename
166      * @param localFileName
167      * @return
168      */
169     public boolean uploadFile(String remotePath, String remoteFilename, String localFileName)
170             throws SftpException, Exception {
171         boolean success = false;
172         FileInputStream fis = null;
173         try {
174             // 更改服务器目录
175             if (null != remotePath && remotePath.trim() != "") {
176                 sftp.cd(remotePath);
177             }
178             File localFile = new File(localFileName);
179             fis = new FileInputStream(localFile);
180             // 发送文件
181             sftp.put(fis, remoteFilename);
182             success = true;
183             System.out.println("成功发送文件,本地路径:" + localFileName);
184         } catch (SftpException e) {
185             System.err.println("发送文件时有SftpException异常!");
186             e.printStackTrace();
187             System.err.println(e.getMessage());
188             throw e;
189         } catch (Exception e) {
190             System.err.println("发送文件时有异常!");
191             System.err.println(e.getMessage());
192             throw e;
193         } finally {
194             try {
195                 if (null != fis) {
196                     fis.close();
197                 }
198                 // 关闭连接
199                 disconnect();
200             } catch (IOException e) {
201                 System.err.println("关闭文件时出错!");
202                 System.err.println(e.getMessage());
203             }
204         }
205         return success;
206     }
207 
208     /**
209      * 上传文件至远程sftp服务器
210      * 
211      * @param remotePath
212      * @param remoteFilename
213      * @param input
214      * @return
215      */
216     public boolean uploadFile(String remotePath, String remoteFilename, InputStream input)
217             throws SftpException, Exception {
218         boolean success = false;
219         try {
220             // 更改服务器目录
221             if (null != remotePath && remotePath.trim() != "") {
222                 sftp.cd(remotePath);
223             }
224 
225             // 发送文件
226             sftp.put(input, remoteFilename);
227             success = true;
228         } catch (SftpException e) {
229             System.err.println("发送文件时有SftpException异常!");
230             e.printStackTrace();
231             System.err.println(e.getMessage());
232             throw e;
233         } catch (Exception e) {
234             System.err.println("发送文件时有异常!");
235             System.err.println(e.getMessage());
236             throw e;
237         } finally {
238             try {
239                 if (null != input) {
240                     input.close();
241                 }
242                 // 关闭连接
243                 disconnect();
244             } catch (IOException e) {
245                 System.err.println("关闭文件时出错!");
246                 System.err.println(e.getMessage());
247             }
248 
249         }
250         return success;
251     }
252 
253     /**
254      * 删除远程文件
255      * 
256      * @param remotePath
257      * @param remoteFilename
258      * @return
259      * @throws Exception
260      */
261     public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
262         boolean success = false;
263         try {
264             // 更改服务器目录
265             if (null != remotePath && remotePath.trim() != "") {
266                 sftp.cd(remotePath);
267             }
268 
269             // 删除文件
270             sftp.rm(remoteFilename);
271             System.err.println("删除远程文件" + remoteFilename + "成功!");
272             success = true;
273         } catch (SftpException e) {
274             System.err.println("删除文件时有SftpException异常!");
275             e.printStackTrace();
276             System.err.println(e.getMessage());
277             return success;
278         } catch (Exception e) {
279             System.err.println("删除文件时有异常!");
280             System.err.println(e.getMessage());
281             return success;
282         } finally {
283             // 关闭连接
284             disconnect();
285         }
286         return success;
287     }
288 
289     /**
290      * 遍历远程文件
291      * 
292      * @param remotePath
293      * @return
294      * @throws Exception
295      */
296     public List<String> listFiles(String remotePath) throws SftpException {
297         List<String> ftpFileNameList = new ArrayList<String>();
298         Vector<LsEntry> sftpFile = sftp.ls(remotePath);
299         LsEntry isEntity = null;
300         String fileName = null;
301         Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
302         while (sftpFileNames.hasNext()) {
303             isEntity = (LsEntry) sftpFileNames.next();
304             fileName = isEntity.getFilename();
305             System.out.println(fileName);
306             ftpFileNameList.add(fileName);
307         }
308         return ftpFileNameList;
309     }
310 
311     /**
312      * 判断路径是否存在
313      * 
314      * @param remotePath
315      * @return
316      * @throws SftpException
317      */
318     public boolean isExist(String remotePath) throws SftpException {
319         boolean flag = false;
320         try {
321             sftp.cd(remotePath);
322             System.out.println("存在路径:" + remotePath);
323             flag = true;
324         } catch (SftpException sException) {
325             
326         } catch (Exception Exception) {
327         }
328         return flag;
329     }
330 
331     public String getHostName() {
332         return hostName;
333     }
334 
335     public void setHostName(String hostName) {
336         this.hostName = hostName;
337     }
338 
339     public int getPort() {
340         return port;
341     }
342 
343     public void setPort(int port) {
344         this.port = port;
345     }
346 
347     public String getUserName() {
348         return userName;
349     }
350 
351     public void setUserName(String userName) {
352         this.userName = userName;
353     }
354 
355     public String getPassword() {
356         return password;
357     }
358 
359     public void setPassword(String password) {
360         this.password = password;
361     }
362 
363     /**
364      * 测试方法
365      * 
366      */
367     public static void main(String[] args) {
368         try {
369             SFTPUtil sftp = new SFTPUtil("192.168.0.177", 22, "weblogic", "weblogic");
370             System.out.println(new StringBuffer().append(" 服务器地址: ")
371                     .append(sftp.getHostName()).append(" 端口:").append(sftp.getPort())
372                     .append("用户名:").append(sftp.getUserName()).append("密码:")
373                     .append(sftp.getPassword().toString()));
374             sftp.connect();
375             if (sftp.isExist("/home/weblogic/project")) {
376                 sftp.listFiles("/home/weblogic/project");
377                 sftp.downloadFile("/home/weblogic/project", "S123456_20150126.csv",
378                         "D:\\S123456_20150126.csv");
379                 // sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt");
380                 // sftp.deleteFile("\\", "test.txt");
381             }
382         } catch (Exception e) {
383             System.out.println("异常信息:" + e.getMessage());
384         }
385     }
386 }

 

以上是关于SFTP工具类的主要内容,如果未能解决你的问题,请参考以下文章

连接获取上传sftp远程目录信息的工具类FtpsFileList

sftp批量上传及批量下载等最全功能的工具类SFTPUtils

CentOS7.6服务器搭建SFTP服务及JAVA工具类

Sftp工具类(跨服务器传输)

elasticsearch代码片段,及工具类SearchEsUtil.java

Java GenericObjectPool 对象池化技术--SpringBoot sftp 连接池工具类