一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - JAVA SFTP文件上傳、下載及批量下載實(shí)例

JAVA SFTP文件上傳、下載及批量下載實(shí)例

2020-08-29 11:54meimao5211 Java教程

本篇文章主要介紹了JAVA SFTP文件上傳、下載及批量下載實(shí)例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

1.jsch官方API查看地址(附件為需要的jar)

http://www.jcraft.com/jsch/

2.jsch簡介

JSch(Java Secure Channel)是一個SSH2的純Java實(shí)現(xiàn)。它允許你連接到一個SSH服務(wù)器,并且可以使用端口轉(zhuǎn)發(fā),X11轉(zhuǎn)發(fā),文件傳輸?shù)龋?dāng)然你也可以集成它的功能到你自己的應(yīng)用程序。

SFTP(Secure File Transfer Protocol)安全文件傳送協(xié)議。可以為傳輸文件提供一種安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務(wù)器的安全方式,但是傳輸效率比普通的FTP要低。

3.api常用的方法:

  • put():      文件上傳
  • get():      文件下載
  • cd():       進(jìn)入指定目錄
  • ls():       得到指定目錄下的文件列表
  • rename():   重命名指定文件或目錄
  • rm():       刪除指定文件
  • mkdir():    創(chuàng)建目錄
  • rmdir():    刪除目錄
  • put和get都有多個重載方法,自己看源代碼

4.對常用方法的使用,封裝成一個util類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
/**
 * sftp工具類
 *
 * @author xxx
 * @date 2014-6-17
 * @time 下午1:39:44
 * @version 1.0
 */
public class SFTPUtils
{
  private static Logger log = Logger.getLogger(SFTPUtils.class.getName());
 
  private String host;//服務(wù)器連接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連接服務(wù)器
   */
  public void connect()
  {
    try
    {
      JSch jsch = new JSch();
      jsch.getSession(username, host, port);
      sshSession = jsch.getSession(username, host, port);
      if (log.isInfoEnabled())
      {
        log.info("Session created.");
      }
      sshSession.setPassword(password);
      Properties sshConfig = new Properties();
      sshConfig.put("StrictHostKeyChecking", "no");
      sshSession.setConfig(sshConfig);
      sshSession.connect();
      if (log.isInfoEnabled())
      {
        log.info("Session connected.");
      }
      Channel channel = sshSession.openChannel("sftp");
      channel.connect();
      if (log.isInfoEnabled())
      {
        log.info("Opening Channel.");
      }
      sftp = (ChannelSftp) channel;
      if (log.isInfoEnabled())
      {
        log.info("Connected to " + host + ".");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
 
  /**
   * 關(guān)閉連接
   */
  public void disconnect()
  {
    if (this.sftp != null)
    {
      if (this.sftp.isConnected())
      {
        this.sftp.disconnect();
        if (log.isInfoEnabled())
        {
          log.info("sftp is closed already");
        }
      }
    }
    if (this.sshSession != null)
    {
      if (this.sshSession.isConnected())
      {
        this.sshSession.disconnect();
        if (log.isInfoEnabled())
        {
          log.info("sshSession is closed already");
        }
      }
    }
  }
 
  /**
   * 批量下載文件
   * @param remotPath:遠(yuǎn)程下載目錄(以路徑符號結(jié)束,可以為相對路徑eg:/assess/sftp/jiesuan_2/2014/)
   * @param localPath:本地保存目錄(以路徑符號結(jié)束,D:\Duansha\sftp\)
   * @param fileFormat:下載文件格式(以特定字符開頭,為空不做檢驗(yàn))
   * @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("本次處理文件個數(shù)不為零,開始下載...fileSize=" + v.size());
        Iterator it = v.iterator();
        while (it.hasNext())
        {
          LsEntry entry = (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);
                }
              }
            }
          }
        }
      }
      if (log.isInfoEnabled())
      {
        log.info("download file is success:remotePath=" + remotePath
            + "and localPath=" + localPath + ",file size is"
            + v.size());
      }
    }
    catch (SftpException e)
    {
      e.printStackTrace();
    }
    finally
    {
      // this.disconnect();
    }
    return filenames;
  }
 
  /**
   * 下載單個文件
   * @param remotPath:遠(yuǎn)程下載目錄(以路徑符號結(jié)束)
   * @param remoteFileName:下載文件名
   * @param localPath:本地保存目錄(以路徑符號結(jié)束)
   * @param localFileName:保存文件名
   * @return
   */
  public boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
  {
    FileOutputStream fieloutput = null;
    try
    {
      // sftp.cd(remotePath);
      File file = new File(localPath + localFileName);
      // mkdirs(localPath + localFileName);
      fieloutput = new FileOutputStream(file);
      sftp.get(remotePath + remoteFileName, fieloutput);
      if (log.isInfoEnabled())
      {
        log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
      }
      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:遠(yuǎn)程保存目錄
   * @param remoteFileName:保存文件名
   * @param localPath:本地上傳目錄(以路徑符號結(jié)束)
   * @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:遠(yuǎn)程保存目錄
   * @param localPath:本地上傳目錄(以路徑符號結(jié)束)
   * @param del:上傳后是否刪除本地文件
   * @return
   */
  public boolean bacthUploadFile(String remotePath, String localPath,
      boolean del)
  {
    try
    {
      connect();
      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());
          }
        }
      }
      if (log.isInfoEnabled())
      {
        log.info("upload file is success:remotePath=" + remotePath
            + "and localPath=" + localPath + ",file size is "
            + files.length);
      }
      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();
    if (rs && log.isInfoEnabled())
    {
      log.info("delete file success from local.");
    }
    return rs;
  }
 
  /**
   * 創(chuàng)建目錄
   * @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());
          // 進(jìn)入并設(shè)置為當(dāng)前目錄
          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:要刪除的文件
   * @param sftp
   */
  public void deleteSFTP(String directory, String deleteFile)
  {
    try
    {
      // sftp.cd(directory);
      sftp.rm(directory + deleteFile);
      if (log.isInfoEnabled())
      {
        log.info("delete file success from sftp.");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
 
  /**
   * 如果目錄不存在就創(chuàng)建目錄
   * @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:要列出的目錄
   * @param sftp
   * @return
   * @throws SftpException
   */
  public Vector listFiles(String directory) throws SftpException
  {
    return sftp.ls(directory);
  }
 
  public String getHost()
  {
    return host;
  }
 
  public void setHost(String host)
  {
    this.host = host;
  }
 
  public String getUsername()
  {
    return username;
  }
 
  public void setUsername(String username)
  {
    this.username = username;
  }
 
  public String getPassword()
  {
    return password;
  }
 
  public void setPassword(String password)
  {
    this.password = password;
  }
 
  public int getPort()
  {
    return port;
  }
 
  public void setPort(int port)
  {
    this.port = port;
  }
 
  public ChannelSftp getSftp()
  {
    return sftp;
  }
 
  public void setSftp(ChannelSftp sftp)
  {
    this.sftp = sftp;
  }
  
  /**測試*/
  public static void main(String[] args)
  {
    SFTPUtils 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 SFTPUtils("10.163.201.115", "tdcp", "tdcp");
      sftp.connect();
      // 下載
      sftp.batchDownLoadFile(sftpPath, localPath, "ASSESS", ".txt", true);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      sftp.disconnect();
    }
  }
}

5.需要的時間輔助類,順帶記下,下次可以直接拿來用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
 * 時間處理工具類(簡單的)
 * @author Aaron
 * @date 2014-6-17
 * @time 下午1:39:44
 * @version 1.0
 */
public class DateUtil {
   /**
   * 默認(rèn)時間字符串的格式
   */
  public static final String DEFAULT_FORMAT_STR = "yyyyMMddHHmmss";
  
  public static final String DATE_FORMAT_STR = "yyyyMMdd";
  
  /**
   * 獲取系統(tǒng)時間的昨天
   * @return
   */
  public static String getSysTime(){
     Calendar ca = Calendar.getInstance(); 
     ca.set(Calendar.DATE, ca.get(Calendar.DATE)-1);
     Date d = ca.getTime();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
     String a = sdf.format(d);
    return a;
  }
  
  /**
   * 獲取當(dāng)前時間
   * @param date
   * @return
   */
  public static String getCurrentDate(String formatStr)
  {
    if (null == formatStr)
    {
      formatStr=DEFAULT_FORMAT_STR;
    }
    return date2String(new Date(), formatStr);
  }
  
  /**
   * 返回年月日
   * @return yyyyMMdd
   */
  public static String getTodayChar8(String dateFormat){
    return DateFormatUtils.format(new Date(), dateFormat);
  }
  
  /**
   * 將Date日期轉(zhuǎn)換為String
   * @param date
   * @param formatStr
   * @return
   */
  public static String date2String(Date date, String formatStr)
  {
    if (null == date || null == formatStr)
    {
      return "";
    }
    SimpleDateFormat df = new SimpleDateFormat(formatStr);
 
    return df.format(date);
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://www.cnblogs.com/meimao5211/p/6376597.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品视频播放 | 欧美性xxxxx 欧美性bbbbbxxxxxddd | 偷拍综合网 | 高清国产在线 | 午夜AV内射一区二区三区红桃视 | 女色在线观看免费视频 | julia ann一hd | 美女一线天| 久久爽狠狠添AV激情五月 | 动漫白丝袜美女羞羞 | 欧美亚洲免费 | 男人狂躁女人下面的视频免费 | 亚洲邪恶天堂影院在线观看 | 千金肉奴隶免费观看 | 免费叼嘿视频 | 国产福利不卡视频在免费 | 国产成人综合一区人人 | 青青青草国产线观 | 四虎一区 | 手机在线伦理片 | 亚洲精品一二三四 | 奇米影视奇米色777欧美 | 美女张开双腿让男人捅 | 天堂漫画破解版 | 好紧好爽再叫浪一点点潘金莲 | 韩国三级 720p| 亚洲男人天 | 北岛玲亚洲一区在线观看 | 9191精品国产观看 | 午夜精品久久久久久久99蜜桃 | 免费一级毛片在线播放 | 天若有情1992国语版完整版 | 男女被爆动漫羞羞动漫 | 日韩高清无砖砖区2022 | 亚洲精品成人在线 | 欧美一级视频在线观看 | 国产欧美一区二区精品性色 | 欧美a级v片在线观看一区 | 亚洲视频免费在线看 | 青青99 | 国产肥臀 |