廢話不多說(shuō),關(guān)鍵代碼如下所示:
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
|
package com.eastrobot.remote; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.eastrobot.util.PropertiesUtil; /** * full.zhang * * */ public abstract class FileRemote { private static final String FTP_MODE = "ftp" ; private static final String SFTP_MODE = "sftp" ; public static String ftproot; public static String mode; public static String host; public static String username; public static String password; public static String port; private static FileRemote client = null ; // 最大一次性下載50個(gè)文件 public static int max = 50 ; private final static Log LOGGER = LogFactory.getLog(FileRemote. class ); public static FileRemote getInstance() { if (client == null ) { ftproot = PropertiesUtil.getString( "transfer.root" ); mode = PropertiesUtil.getString( "transfer.mode" ); host = PropertiesUtil.getString( "transfer.host" ); username = PropertiesUtil.getString( "transfer.username" ); password = PropertiesUtil.getString( "transfer.password" ); port = PropertiesUtil.getString( "transfer.port" ); if (mode.equals(FTP_MODE)) { client = new FileFtpRemote(); } else if (mode.equals(SFTP_MODE)) { client = new FileSftpRemote(); } } return client; } /** * 執(zhí)行定時(shí)任務(wù) */ public void process() { LOGGER.debug( "----------------------------------------進(jìn)入定時(shí)下載遠(yuǎn)程文件" ); // 創(chuàng)建線程池 ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute( new Runnable() { @Override public void run() { // 建立連接 initFtpInfo(host, port, username, password); // 遠(yuǎn)程服務(wù)所有源文件路徑集合 List<String> listSourcePath = listRemoteFilePath(ftproot); if (listSourcePath.isEmpty()) { LOGGER.debug( "____________________釋放連接" ); client.closeConnection(); return ; } if (listSourcePath.size() > max) { listSourcePath = listSourcePath.subList( 0 , max); } for (String path : listSourcePath) { downloadRemoteFile(path); } LOGGER.debug( "____________________釋放連接" ); client.closeConnection(); } }); exec.shutdown(); } /** * 初始化連接 * * @param host * @param port * @param username * @param password * @throws Exception * @return */ public abstract void initFtpInfo(String host, String port, String username, String password); /** * 下載遠(yuǎn)程服務(wù)下文件到本地服務(wù) * * @param path * @return * @throws Exception */ public abstract void downloadRemoteFile(String filePath); /** * 獲取遠(yuǎn)程服務(wù)下指定目錄下的所有文件路徑集合(包含子目錄下文件) * * @param path * @return */ public abstract List<String> listRemoteFilePath(String path); /** * 釋放連接 */ public abstract void closeConnection(); } [java] view plain copy package com.eastrobot.remote; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.eastrobot.command.Commander; public class FileFtpRemote extends FileRemote { protected FTPClient ftpClient; private String encoding = "UTF-8" ; private boolean binaryTransfer = true ; private final static Log LOGGER = LogFactory.getLog(FileFtpRemote. class ); @Override public void initFtpInfo(String host, String port, String username, String password) { try { // 構(gòu)造一個(gè)FtpClient實(shí)例 ftpClient = new FTPClient(); // 設(shè)置字符集 ftpClient.setControlEncoding(encoding); // 連接FTP服務(wù)器 ftpClient.connect(host, StringUtils.isNotBlank(port) ? Integer.valueOf(port) : 21 ); // 連接后檢測(cè)返回碼來(lái)校驗(yàn)連接是否成功 int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { // 登陸到ftp服務(wù)器 if (ftpClient.login(username, password)) { setFileType(); } ftpClient.login(username, password); } else { ftpClient.disconnect(); LOGGER.error( "ftp服務(wù)拒絕連接!" ); } } catch (Exception e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); // 斷開(kāi)連接 } catch (IOException e1) { LOGGER.error( "ftp服務(wù)連接斷開(kāi)失敗!" ); } } LOGGER.error( "ftp服務(wù)連接失敗!" ); } } /** * 設(shè)置文件傳輸類型 */ private void setFileType() { try { if (binaryTransfer) { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); } else { ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE); } } catch (IOException e) { e.printStackTrace(); } } @Override public void downloadRemoteFile(String filePath) { if (StringUtils.endsWith(filePath, "/" ) || StringUtils.endsWith(filePath, File.separator)) { filePath = filePath.substring( 0 , filePath.length() - 1 ); } File saveFile = new File(filePath); if (saveFile.exists()) { return ; } // 文件所在目錄 String path = filePath.substring( 0 , filePath.lastIndexOf( "/" )); if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } OutputStream output = null ; try { // 創(chuàng)建目標(biāo)文件路徑 if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } saveFile.createNewFile(); // 轉(zhuǎn)移到FTP服務(wù)器目錄 ftpClient.changeWorkingDirectory(path); output = new FileOutputStream(saveFile); ftpClient.retrieveFile(filePath, output); } catch (IOException e) { LOGGER.debug( "文件:" + filePath + "______________________下載失敗!" ); e.printStackTrace(); } finally { LOGGER.debug( "文件:" + filePath + "______________________下載成功!" ); IOUtils.closeQuietly(output); } } @Override public List<String> listRemoteFilePath(String path) { List<String> list = new ArrayList<String>(); try { if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } boolean changedir = ftpClient.changeWorkingDirectory(path); if (changedir) { ftpClient.setControlEncoding(encoding); FTPFile[] files = ftpClient.listFiles(); for (FTPFile file : files) { if (list.size() >= max) { break ; } if (file.isDirectory()) { if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } list.addAll( this .listRemoteFilePath(path + file.getName())); } else if (changedir) { if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } File saveFile = new File(path + file.getName()); if (!saveFile.exists()) { list.add(path + file.getName()); } } } } } catch (Exception e) { e.printStackTrace(); } return list; } @Override public void closeConnection() { if (ftpClient != null ) { try { ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } } } [java] view plain copy package com.eastrobot.remote; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Vector; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.eastrobot.command.Commander; 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; public class FileSftpRemote extends FileRemote { protected Session session = null ; protected ChannelSftp channel = null ; private final static Log LOGGER = LogFactory.getLog(FileSftpRemote. class ); @Override public void initFtpInfo(String host, String port, String username, String password) { try { JSch jsch = new JSch(); // 創(chuàng)建JSch對(duì)象 session = jsch.getSession(username, host, StringUtils.isNotBlank(port) ? Integer.valueOf(port) : 22 ); session.setPassword(password); // 設(shè)置密碼 Properties config = new Properties(); config.put( "StrictHostKeyChecking" , "no" ); session.setConfig(config); // 為Session對(duì)象設(shè)置properties session.setTimeout( 60000 ); // 設(shè)置timeout時(shí)間 session.connect(); // 通過(guò)Session建立鏈接 Channel chan = session.openChannel( "sftp" ); // 打開(kāi)SFTP通道 chan.connect(); // 建立SFTP通道的連接 channel = (ChannelSftp) chan; } catch (Exception e) { LOGGER.error( "sftp連接失敗" ); e.printStackTrace(); } } @Override public void downloadRemoteFile(String filePath) { if (StringUtils.endsWith(filePath, "/" ) || StringUtils.endsWith(filePath, File.separator)) { filePath = filePath.substring( 0 , filePath.length() - 1 ); } File saveFile = new File(filePath); FileOutputStream output = null ; try { if (saveFile.exists()) { return ; } // 創(chuàng)建目標(biāo)文件路徑 if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } saveFile.createNewFile(); // 文件所在目錄 String path = filePath.substring( 0 , filePath.lastIndexOf( "/" )); if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } channel.cd(path); channel.get(filePath, new FileOutputStream(saveFile)); LOGGER.debug( "文件:" + filePath + "____________________________________________下載成功!" ); } catch (Exception e) { LOGGER.debug( "文件:" + filePath + "____________________________________________下載失敗!" ); e.printStackTrace(); } finally { IOUtils.closeQuietly(output); } } @SuppressWarnings ( "unchecked" ) @Override public List<String> listRemoteFilePath(String path) { List<String> list = new ArrayList<String>(); Vector<LsEntry> v = null ; try { if (!StringUtils.endsWith(path, "/" ) && StringUtils.endsWith(path, File.separator)) { path = path + File.separator; } v = channel.ls(path); } catch (SftpException e) { e.printStackTrace(); } for (LsEntry lsEntry : v) { if (list.size() >= max) { break ; } if (! "." .equals(lsEntry.getFilename()) && ! ".." .equals(lsEntry.getFilename())) { SftpATTRS attrs = lsEntry.getAttrs(); if (attrs.isDir()) { if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } list.addAll( this .listRemoteFilePath(path + lsEntry.getFilename())); } else { if (!StringUtils.endsWith(path, "/" ) && !StringUtils.endsWith(path, File.separator)) { if (Commander.isLinux) { path = path + File.separator; } else { path = path + "/" ; } } File saveFile = new File(path + lsEntry.getFilename()); if (!saveFile.exists()) { list.add(path + lsEntry.getFilename()); } } } } return list; } @Override public void closeConnection() { try { if (channel != null ) { channel.quit(); channel.disconnect(); } if (session != null ) { session.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } public Session getSession() { return session; } public void setSession(Session session) { this .session = session; } public ChannelSftp getChannel() { return channel; } public void setChannel(ChannelSftp channel) { this .channel = channel; } } |
以上所述是小編給大家介紹的sftp和ftp 根據(jù)配置遠(yuǎn)程服務(wù)器地址下載文件到當(dāng)前服務(wù),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/zhangqinfu/article/details/52931871