java ftp操作类
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
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[i].exists()) {
215 continue;
216 }
217 if (sourceFile[i].isDirectory()) {
218 this.upload(sourceFile[i].getPath(), sourceFile[i]
219 .getName(), path + "/" + newName);
220 } else {
221 this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
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 }