设为首页 收藏本站
查看: 652|回复: 0

java ftp操作类

[复制链接]

尚未签到

发表于 2015-5-28 10:27:54 | 显示全部楼层 |阅读模式
  


DSC0000.gif DSC0001.gif ftputil



  1 import java.io.BufferedReader;
  2  import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.util.ArrayList;
  9 import java.util.List;
10 import java.util.StringTokenizer;
11
12 import sun.net.TelnetInputStream;
13 import sun.net.TelnetOutputStream;
14 import sun.net.ftp.FtpClient;
15
19 public class FtpUtil {
20
21     private String ip = "";
22     private String userName = "";
23     private String password = "";
24     private int port = -1;
25     private String path = "";
26     FtpClient ftpClient = null;
27     OutputStream os = null;
28     FileInputStream is = null;
29
30     public FtpUtil(String serverIP, String userName, String password) {
31         this.ip = serverIP;
32         this.userName = userName;
33         this.password = password;
34     }
35
36     public FtpUtil(String serverIP, int port, String userName, String password) {
37         this.ip = serverIP;
38         this.userName = userName;
39         this.password = password;
40         this.port = port;
41     }
42
43     public boolean connectServer() {
44         ftpClient = new FtpClient();
45         try {
46             if (this.port != -1) {
47                 ftpClient.openServer(this.ip, this.port);
48             } else {
49                 ftpClient.openServer(this.ip);
50             }
51             ftpClient.login(this.userName, this.password);
52             if (this.path.length() != 0) {
53                 ftpClient.cd(this.path);
54             }
55             ftpClient.binary();
56             return true;
57         } catch (IOException e) {
58             e.printStackTrace();
59             return false;
60         }
61     }
62
63     public boolean closeServer() {
64         try {
65             if (is != null) {
66                 is.close();
67             }
68             if (os != null) {
69                 os.close();
70             }
71             if (ftpClient != null) {
72                 ftpClient.closeServer();
73             }
74             return true;
75         } catch (IOException e) {
76             e.printStackTrace();
77             return false;
78         }
79     }
80
81     /**
82      * judge if dir exist on ftp
83      *
84      * @param dir
85      * @return
86      */
87     public boolean isDirExist(String dir) {
88         String pwd = "";
89         try {
90             pwd = ftpClient.pwd();
91             ftpClient.cd(dir);
92             ftpClient.cd(pwd);
93         } catch (Exception e) {
94             return false;
95         }
96         return true;
97     }
98
99     /**
100      * create directory on ftp
101      *
102      * @param dir
103      * @return
104      */
105     private boolean createDir(String dir) {
106         try {
107             ftpClient.ascii();
108             StringTokenizer s = new StringTokenizer(dir, "/"); // sign
109             s.countTokens();
110             String pathName = ftpClient.pwd();
111             while (s.hasMoreElements()) {
112                 pathName = pathName + "/" + (String) s.nextElement();
113                 try {
114                     ftpClient.sendServer("MKD " + pathName + "\r\n");
115                 } catch (Exception e) {
116                     e = null;
117                     return false;
118                 }
119                 ftpClient.readServerResponse();
120             }
121             ftpClient.binary();
122             return true;
123         } catch (IOException e1) {
124             e1.printStackTrace();
125             return false;
126         }
127     }
128
129     /**
130      * upload file or folder (auto generate ftp filename)
131      *
132      * @param name
133      * @return
134      */
135     public boolean upload(String name) {
136         String newname = "";
137         if (name.indexOf("/") > -1) {
138             newname = name.substring(name.lastIndexOf("/") + 1);
139         } else {
140             newname = name;
141         }
142         return upload(name, newname);
143     }
144
145     /**
146      * upload file or folder
147      *
148      * @param name
149      * @param newName
150      * @return
151      */
152     public boolean upload(String name, String newName) {
153         try {
154             String savefilename = new String(name.getBytes("ISO-8859-1"), "GBK");
155             File file_in = new File(savefilename);
156             if (!file_in.exists()) {
157                 throw new Exception("file or folder" + file_in.getName()
158                         + "not exist!");
159             }
160             if (file_in.isDirectory()) {
161                 upload(file_in.getPath(), newName, ftpClient.pwd());
162             } else {
163                 uploadFile(file_in.getPath(), newName);
164             }
165
166             if (is != null) {
167                 is.close();
168             }
169             if (os != null) {
170                 os.close();
171             }
172             return true;
173         } catch (Exception e) {
174             e.printStackTrace();
175             System.err.println("Exception e in Ftp upload(): " + e.toString());
176             return false;
177         } finally {
178             try {
179                 if (is != null) {
180                     is.close();
181                 }
182                 if (os != null) {
183                     os.close();
184                 }
185             } catch (IOException e) {
186                 e.printStackTrace();
187             }
188         }
189     }
190
191     /**
192      * upload file/folder to ftp
193      *
194      * @param name
195      * @param newName
196      * @param path
197      * @throws Exception
198      */
199     private void upload(String name, String newName, String path)
200             throws Exception {
201         String savefilename = new String(name.getBytes("ISO-8859-1"), "GBK");
202         File file_in = new File(savefilename);
203         if (!file_in.exists()) {
204             throw new Exception("file or folder" + file_in.getName()
205                     + "!not exist");
206         }
207         if (file_in.isDirectory()) {
208             if (!isDirExist(newName)) {
209                 createDir(newName);
210             }
211             ftpClient.cd(newName);
212             File sourceFile[] = file_in.listFiles();
213             for (int i = 0; i < sourceFile.length; i++) {
214                 if (!sourceFile.exists()) {
215                     continue;
216                 }
217                 if (sourceFile.isDirectory()) {
218                     this.upload(sourceFile.getPath(), sourceFile
219                             .getName(), path + "/" + newName);
220                 } else {
221                     this.uploadFile(sourceFile.getPath(), sourceFile
222                             .getName());
223                 }
224             }
225         } else {
226             uploadFile(file_in.getPath(), newName);
227         }
228         ftpClient.cd(path);
229     }
230
231     /**
232      * upload local file/folder to ftp
233      *
234      * @param filename
235      * @param newname
236      * @return
237      * @throws Exception
238      */
239     public long uploadFile(String filename, String newname) throws Exception {
240         long result = 0;
241         TelnetOutputStream os = null;
242         FileInputStream is = null;
243         try {
244             java.io.File file_in = new java.io.File(filename);
245             if (!file_in.exists())
246                 return -1;
247             os = ftpClient.put(newname);
248             result = file_in.length();
249             is = new FileInputStream(file_in);
250             byte[] bytes = new byte[1024];
251             int c;
252             while ((c = is.read(bytes)) != -1) {
253                 os.write(bytes, 0, c);
254             }
255         } finally {
256             if (is != null) {
257                 is.close();
258             }
259             if (os != null) {
260                 os.close();
261             }
262         }
263         return result;
264     }
265
266     /**
267      * download ftp file to local
268      *
269      * @param filename
270      * @param newfilename
271      * @return
272      */
273     public long downloadFile(String filename, String newfilename) {
274         long result = 0;
275         TelnetInputStream is = null;
276         FileOutputStream os = null;
277         try {
278             is = ftpClient.get(filename);
279             java.io.File outfile = new java.io.File(newfilename);
280             os = new FileOutputStream(outfile);
281             byte[] bytes = new byte[1024];
282             int c;
283             while ((c = is.read(bytes)) != -1) {
284                 os.write(bytes, 0, c);
285                 result = result + c;
286             }
287         } catch (IOException e) {
288             e.printStackTrace();
289         } finally {
290             try {
291                 if (is != null) {
292                     is.close();
293                 }
294                 if (os != null) {
295                     os.close();
296                 }
297             } catch (IOException e) {
298                 e.printStackTrace();
299             }
300         }
301         return result;
302     }
303
304     /**
305      * download remote directory to local
306      *
307      * @param remoteDir
308      * @param localDir
309      * @return
310      */
311     public long downloadDir(String remoteDir, String localDir) {
312         long result = 0;
313         try {
314             if (!(new File(localDir).isDirectory())) {
315                 new File(localDir).mkdir();
316             }
317
318             List list = this.getFileList(remoteDir);
319             for (int i = 0; i < list.size(); i++) {
320                 String name = list.get(i).toString();
321
322                 if (isDirExist(name)) {
323                     // downloadDir
324                     System.out.println(name + " directory");
325                     downloadDir(name, localDir + "/" + getFileName(name));
326                 } else {
327                     System.out.println("in");
328                     downloadFile(name, localDir + "/" + getFileName(name));
329                 }
330             }
331         } catch (Exception e) {
332             e.printStackTrace();
333         }
334         return result;
335     }
336
337     /**
338      * get file name
339      *
340      * @param fullName
341      * @return
342      */
343     private String getFileName(String fullName) {
344         String fileName = "";
345         if (fullName.indexOf("/") > -1) {
346             fileName = fullName.substring(fullName.lastIndexOf("/") + 1);
347         } else {
348             fileName = fullName;
349         }
350         return fileName;
351     }
352
353     /**
354      * get file list in the directory
355      *
356      * @param path
357      * @return
358      */
359     public List getFileList(String path) {
360         List list = new ArrayList();
361         BufferedReader br;
362         try {
363             br = new BufferedReader(new InputStreamReader(ftpClient
364                     .nameList(this.path + path)));
365             String filename = "";
366             while ((filename = br.readLine()) != null) {
367                 list.add(filename);
368             }
369         } catch (IOException e) {
370             e.printStackTrace();
371         }
372         return list;
373     }
374
375     /**
376      * download ftp directory to local
377      *
378      * @param ftpIp
379      * @param ftpPort
380      * @param ftpUser
381      * @param ftpPassword
382      * @param ftpDir
383      * @param localDir
384      */
385     public static void getDirFromFtp(String ftpIp, int ftpPort, String ftpUser,
386             String ftpPassword, String ftpDir, String localDir) {
387         FtpUtil ftp = new FtpUtil(ftpIp, ftpPort, ftpUser, ftpPassword);
388         ftp.connectServer();
389         ftp.downloadDir(ftpDir, localDir);
390         ftp.closeServer();
391     }
392
393     public static void main(String[] args) {
394         FtpUtil ftp = new FtpUtil("10.2.23.122", 2121, "user", "password");
395         ftp.connectServer();
396         ftp.downloadDir("test", "e:/temp");
397         ftp.closeServer();
398     }
399 }
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-71414-1-1.html 上篇帖子: 利用Indy的TIdFtp控件实现FTP协议 下篇帖子: Linux or unix FTP 上传下载实例
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表