SFTP多文件上传,删除

  公司项目中需要把项目的相关文件上传到服务器的tomcat中,需要在项目中进行以下几步操作:

  1.添加项目信息,包括名称,描述,服务器ip,sftp的用户名,密码,端口号等,存在配置,部署,删除等操作

  2.配置:显示出文件信息,包括文件路径,目标路径,类型(上传,删除),状态(是否部署),

  3.点击部署时进行自动的部署,可以是文件上传,也可以是相关文件的删除

 

结合网上有关sftp完成的sftp工具类,只使用了多文件上传和文件删除功能,其他没有进行测试,多文件上传需要本地路径和远程路径参数,文件夹删除需要远程路径参数

  1 package MyUtils;
  2 
  3 import com.jcraft.jsch.*;
  4 import org.apache.log4j.Logger;
  5 
  6 import java.io.*;
  7 import java.util.ArrayList;
  8 import java.util.Iterator;
  9 import java.util.List;
 10 import java.util.Vector;
 11 
 12 /**
 13  * sftp工具类
 14  *
 15 
 16  */
 17 public class SFTPUtils {
 18     private static Logger log = Logger.getLogger(SFTPUtils.class.getName());
 19     private static ChannelSftp sftp = null;
 20     private static Session sshSession = null;
 21     private static Integer i = 0;
 22 
 23 
 24     /**
 25      * 通过SFTP连接服务器
 26      */
 27     public static void connect(String ip, String username, String password, Integer port) throws Exception {
 28 
 29         JSch jsch = new JSch();
 30         try {
 31             if (port <= 0) {
 32                 // 连接服务器,采用默认端口
 33                 sshSession = jsch.getSession(username, ip);
 34             } else {
 35                 // 采用指定的端口连接服务器
 36                 sshSession = jsch.getSession(username, ip, port);
 37             }
 38 
 39             // 如果服务器连接不上,则抛出异常
 40             if (sshSession == null) {
 41                 throw new Exception("服务器异常");
 42             }
 43 
 44             // 设置登陆主机的密码
 45             sshSession.setPassword(password);// 设置密码
 46             // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
 47             sshSession.setConfig("StrictHostKeyChecking", "no");
 48             // 设置登陆超时时间
 49             sshSession.connect(300000);
 50             Channel channel = sshSession.openChannel("sftp");
 51             channel.connect();
 52 
 53             sftp = (ChannelSftp) channel;
 54 
 55         } catch (Exception e) {
 56             e.printStackTrace();
 57             throw e;
 58         }
 59     }
 60 
 61     /**
 62      * 关闭连接
 63      */
 64     public static void disconnect() {
 65         if (sftp != null) {
 66             if (sftp.isConnected()) {
 67                 sftp.disconnect();
 68                 if (log.isInfoEnabled()) {
 69                     log.info("已关闭sftp");
 70                 }
 71             }
 72         }
 73         if (sshSession != null) {
 74             if (sshSession.isConnected()) {
 75                 sshSession.disconnect();
 76                 if (log.isInfoEnabled()) {
 77                     log.info("已关闭sshSession");
 78                 }
 79             }
 80         }
 81     }
 82 
 83     /**
 84      * 批量下载文件
 85      *
 86      * @param remotePath:远程下载目录(以路径符号结束)
 87      *
 88      * @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
 89      *
 90      * @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
 91      *
 92      * @param fileEndFormat:下载文件格式(文件格式)
 93      * @param del:下载后是否删除sftp文件
 94      * @return
 95      */
 96     public List<String> batchDownLoadFile(String remotePath, String localPath,
 97                                           String fileFormat, String fileEndFormat, boolean del) throws SftpException {
 98         List<String> filenames = new ArrayList<String>();
 99 
100         Vector v = sftp.ls(remotePath);
101         if (v.size() > 0) {
102             System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
103             Iterator it = v.iterator();
104             while (it.hasNext()) {
105                 ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
106                 String filename = entry.getFilename();
107                 SftpATTRS attrs = entry.getAttrs();
108                 if (!attrs.isDir()) {
109                     boolean flag = false;
110                     String localFileName = localPath + filename;
111                     fileFormat = fileFormat == null ? "" : fileFormat
112                             .trim();
113                     fileEndFormat = fileEndFormat == null ? ""
114                             : fileEndFormat.trim();
115                     // 三种情况
116                     if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
117                         if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
118                             flag = downloadFile(remotePath, filename, localPath, filename);
119                             if (flag) {
120                                 filenames.add(localFileName);
121                                 if (flag && del) {
122                                     deleteSFTP(remotePath);
123                                 }
124                             }
125                         }
126                     } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
127                         if (filename.startsWith(fileFormat)) {
128                             flag = downloadFile(remotePath, filename, localPath, filename);
129                             if (flag) {
130                                 filenames.add(localFileName);
131                                 if (flag && del) {
132                                     deleteSFTP(remotePath);
133                                 }
134                             }
135                         }
136                     } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
137                         if (filename.endsWith(fileEndFormat)) {
138                             flag = downloadFile(remotePath, filename, localPath, filename);
139                             if (flag) {
140                                 filenames.add(localFileName);
141                                 if (flag && del) {
142                                     deleteSFTP(remotePath);
143                                 }
144                             }
145                         }
146                     } else {
147                         flag = downloadFile(remotePath, filename, localPath, filename);
148                         if (flag) {
149                             filenames.add(localFileName);
150                             if (flag && del) {
151                                 deleteSFTP(remotePath);
152                             }
153                         }
154                     }
155                 }
156             }
157         }
158         if (log.isInfoEnabled()) {
159             log.info("download file is success:remotePath=" + remotePath
160                     + "and localPath=" + localPath + ",file size is"
161                     + v.size());
162         }
163 
164         return filenames;
165     }
166 
167     /**
168      * 下载单个文件
169      *
170      * @param remotePath:远程下载目录(以路径符号结束)e
171      * @param remoteFileName:下载文件名
172      * @param localPath:本地保存目录(以路径符号结束)
173      * @param localFileName:保存文件名
174      * @return
175      */
176     public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
177         FileOutputStream fieloutput = null;
178         try {
179             // sftp.cd(remotePath);
180             File file = new File(localPath + localFileName);
181             // mkdirs(localPath + localFileName);
182             fieloutput = new FileOutputStream(file);
183             sftp.get(remotePath + remoteFileName, fieloutput);
184             if (log.isInfoEnabled()) {
185                 log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
186             }
187             return true;
188         } catch (FileNotFoundException e) {
189             e.printStackTrace();
190         } catch (SftpException e) {
191             e.printStackTrace();
192         } finally {
193             if (null != fieloutput) {
194                 try {
195                     fieloutput.close();
196                 } catch (IOException e) {
197                     e.printStackTrace();
198                 }
199             }
200         }
201         return false;
202     }
203 
204     /**
205      * 上传单个文件
206      *
207      * @param remotePath:远程保存目录
208      * @param localPath:本地上传目录(以路径符号结束)
209      * @return
210      */
211     public static void uploadFile(String remotePath, String localPath) throws Exception {
212         FileInputStream in = null;
213         File localFile = new File(localPath);
214         sftp.cd(remotePath);
215         in = new FileInputStream(localFile);
216         sftp.put(in, localFile.getName());
217 
218         if (in != null) {
219             in.close();
220         }
221     }
222 
223     /**
224      * 批量上传文件
225      *
226      * @param remotePath:远程保存目录
227      * @param localPath:本地上传目录(以路径符号结束)
228      * @return
229      */
230     public static boolean bacthUploadFile(String remotePath, String localPath) throws Exception {
231         File localFile = new File(localPath);
232         boolean flag = true;
233         //进入远程路径
234         try {
235             if (!isDirExist(remotePath)) {
236                 sftp.mkdir(remotePath);
237                 sftp.cd(remotePath);
238             } else {
239                 sftp.cd(remotePath);
240             }
241             //本地文件上传
242             File file = new File(localPath);
243             //本地文件上传方法
244             copyFile(file, sftp.pwd());
245 
246 
247         } catch (Exception e) {
248             e.printStackTrace();
249             flag = false;
250             throw e;
251         }
252 
253         return flag;
254     }
255 
256     private static void copyFile(File file, String pwd) throws Exception {
257         if (file.isDirectory()) {
258             File[] list = file.listFiles();
259             String fileName = file.getName();
260             sftp.cd(pwd);
261             System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);
262             sftp.mkdir(fileName);
263             System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
264             //远程路径发生改变
265             pwd = pwd + "/" + file.getName();
266             sftp.cd(file.getName());
267 
268             for (int i = 0; i < list.length; i++) {
269                 copyFile(list[i], pwd);
270             }
271         } else {
272             //不是目录,直接进入改变后的远程路径,进行上传
273             sftp.cd(pwd);
274 
275             System.out.println("正在复制文件:" + file.getAbsolutePath());
276             InputStream instream = null;
277             OutputStream outstream = null;
278             outstream = sftp.put(file.getName());
279             instream = new FileInputStream(file);
280 
281             byte b[] = new byte[1024];
282             int n;
283             while ((n = instream.read(b)) != -1) {
284                 outstream.write(b, 0, n);
285             }
286 
287             outstream.flush();
288             outstream.close();
289             instream.close();
290 
291         }
292 
293     }
294 
295     /**
296      * 删除本地文件
297      *
298      * @param filePath
299      * @return
300      */
301     public boolean deleteFile(String filePath) {
302         File file = new File(filePath);
303         if (!file.exists()) {
304             return false;
305         }
306 
307         if (!file.isFile()) {
308             return false;
309         }
310         boolean rs = file.delete();
311         if (rs && log.isInfoEnabled()) {
312             log.info("delete file success from local.");
313         }
314         return rs;
315     }
316 
317     /**
318      * 创建目录
319      *
320      * @param createpath
321      * @return
322      */
323     public static void createDir(String createpath) {
324         try {
325             if (isDirExist(createpath)) {
326                 sftp.cd(createpath);
327             }
328             String pathArry[] = createpath.split("/");
329             StringBuffer filePath = new StringBuffer("/");
330             for (String path : pathArry) {
331                 if (path.equals("")) {
332                     continue;
333                 }
334                 filePath.append(path + "/");
335                 if (isDirExist(filePath.toString())) {
336                     sftp.cd(filePath.toString());
337                 } else {
338                     // 建立目录
339                     sftp.mkdir(filePath.toString());
340                     // 进入并设置为当前目录
341                     sftp.cd(filePath.toString());
342                 }
343 
344             }
345         } catch (SftpException e) {
346             e.printStackTrace();
347         }
348     }
349 
350     /**
351      * 判断目录是否存在
352      *
353      * @param directory
354      * @return
355      */
356     public static boolean isDirExist(String directory) {
357         try {
358             Vector<?> vector = sftp.ls(directory);
359             if (null == vector) {
360                 return false;
361             } else {
362                 return true;
363             }
364         } catch (Exception e) {
365             return false;
366         }
367     }
368 
369     /**
370      * 删除stfp文件
371      *
372      * @param directory:要删除文件所在目录
373      */
374     public static void deleteSFTP(String directory) {
375         try {
376             if (isDirExist(directory)) {
377                 Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
378                 if (vector.size() == 1) { // 文件,直接删除
379                     sftp.rm(directory);
380                 } else if (vector.size() == 2) { // 空文件夹,直接删除
381                     sftp.rmdir(directory);
382                 } else {
383                     String fileName = "";
384                     // 删除文件夹下所有文件
385                     for (ChannelSftp.LsEntry en : vector) {
386                         fileName = en.getFilename();
387                         if (".".equals(fileName) || "..".equals(fileName)) {
388                             continue;
389                         } else {
390                             deleteSFTP(directory + "/" + fileName);
391                         }
392                     }
393                     // 删除文件夹
394                     sftp.rmdir(directory);
395                 }
396             }
397         } catch (Exception e) {
398             e.printStackTrace();
399         }
400     }
401 
402     /**
403      * 如果目录不存在就创建目录
404      *
405      * @param path
406      */
407     public void mkdirs(String path) {
408         File f = new File(path);
409 
410         String fs = f.getParent();
411 
412         f = new File(fs);
413 
414         if (!f.exists()) {
415             f.mkdirs();
416         }
417     }
418 
419 
420 
421     /**
422      * 测试
423      */
424     public static void main(String[] args) {
425         // 本地存放地址
426         String localPath = "F:\\java\\src\\main\\webapp\\resources";
427         // Sftp下载路径
428         String sftpPath = "/home/sftp/";
429         List<String> filePathList = new ArrayList<String>();
430         try {
431             connect("111.16.123.12", "ftptest1", "123456", 22);
432             //deleteSFTP(sftpPath);
433             // 上传
434             //bacthUploadFile(sftpPath, localPath);
435             //deleteSFTP("/home/ftp/ff");
436         } catch (Exception e) {
437             e.printStackTrace();
438         } finally {
439             sftp.disconnect();
440         }
441     }
442 }

 

posted @ 2018-01-04 17:27  生根  阅读(13884)  评论(0编辑  收藏  举报