FTPClient上传下载等

Posted 小泉哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FTPClient上传下载等相关的知识,希望对你有一定的参考价值。

  1 package com.lct.conference.controller.MonitorManagement.cofer;
  2 
  3 import org.apache.commons.net.ftp.FTPClient;
  4 import org.apache.commons.net.ftp.FTPFile;
  5 import org.apache.commons.net.ftp.FTPReply;
  6 
  7 import com.lct.conference.entity.filemngt.FileManageRes;
  8 
  9 
 10 import java.io.*;
 11 import java.net.SocketException;
 12 import java.util.ArrayList;
 13 
 14 
 15 public class FtpUtil {
 16     /**
 17      * 获取FTPClient对象
 18      *
 19      * @param ftpHost     FTP主机服务器
 20      * @param ftpPassword FTP 登录密码
 21      * @param ftpUserName FTP登录用户名
 22      * @param ftpPort     FTP端口 默认为21
 23      * @return
 24      */
 25     public static FTPClient getFTPClient(FileManageRes ftpinfo) {
 26         FTPClient ftpClient = new FTPClient();
 27         String ftpHost = ftpinfo.getFtpHost();
 28         String ftpUserName = ftpinfo.getFtpUserName();
 29         String ftpPassword = ftpinfo.getFtpPassword();
 30         int ftpPort = ftpinfo.getFtpPort();
 31         try {
 32             ftpClient = new FTPClient();
 33             ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
 34             ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
 35             if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
 36                 System.out.println("未连接到FTP,用户名或密码错误。");
 37                 ftpClient.disconnect();
 38             } else {
 39                 System.out.println("FTP连接成功。");
 40             }
 41         } catch (SocketException e) {
 42             e.printStackTrace();
 43             System.out.println("FTP的IP地址可能错误,请正确配置。");
 44         } catch (IOException e) {
 45             e.printStackTrace();
 46             System.out.println("FTP的端口错误,请正确配置。");
 47         }
 48         return ftpClient;
 49     }
 50 
 51     /*
 52      * 从FTP服务器下载文件
 53      *
 54      * @param ftpHost FTP IP地址
 55      * @param ftpUserName FTP 用户名
 56      * @param ftpPassword FTP用户名密码
 57      * @param ftpPort FTP端口
 58      * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
 59      * @param localPath 下载到本地的位置 格式:H:/download
 60      * @param fileName 文件名称
 61      */
 62     public static  boolean downloadFtpFile(String ftpPath, String localPath,
 63                                        String fileName,FileManageRes ftpinfo) {
 64         boolean flag = false;
 65         FTPClient ftpClient = null;
 66 
 67         try {
 68             ftpClient = getFTPClient(ftpinfo);
 69             ftpClient.setControlEncoding("UTF-8"); // 中文支持
 70             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
 71             ftpClient.enterLocalPassiveMode();
 72             ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"),"iso-8859-1"));
 73             
 74 
 75             File localFile = new File(localPath + File.separatorChar + fileName);
 76             OutputStream os = new FileOutputStream(localFile);
 77             flag = ftpClient.retrieveFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), os);
 78             os.close();
 79             ftpClient.logout();
 80         } catch (FileNotFoundException e) {
 81             System.out.println("没有找到" + ftpPath + "文件");
 82             e.printStackTrace();
 83         } catch (SocketException e) {
 84             System.out.println("连接FTP失败.");
 85             e.printStackTrace();
 86         } catch (IOException e) {
 87             e.printStackTrace();
 88             System.out.println("文件读取错误。");
 89             e.printStackTrace();
 90         }
 91         return flag;
 92     }
 93 
 94     /**
 95      * Description: 向FTP服务器上传文件
 96      * @param ftpHost FTP服务器hostname
 97      * @param ftpUserName 账号
 98      * @param ftpPassword 密码
 99      * @param ftpPort 端口
100      * @param ftpPath  FTP服务器中文件所在路径 格式: ftptest/aa
101      * @param fileName ftp文件名称
102      * @param input 文件流
103      * @return 成功返回true,否则返回false
104      */
105     public static boolean uploadFile(String ftpPath,String fileName,InputStream input,FileManageRes ftpinfo) {
106         boolean success = false;
107         FTPClient ftpClient = null;
108         try {
109             int reply;
110             ftpClient = getFTPClient(ftpinfo);
111             reply = ftpClient.getReplyCode();
112             if (!FTPReply.isPositiveCompletion(reply)) {
113                 ftpClient.disconnect();
114                 return success;
115             }
116             ftpClient.setControlEncoding("UTF-8"); // 中文支持
117             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
118             ftpClient.enterLocalPassiveMode();
119             ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"),"iso-8859-1"));
120             ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), input);
121             input.close();
122             ftpClient.logout();
123             success = true;
124         } catch (IOException e) {
125             e.printStackTrace();
126         } finally {
127             if (ftpClient.isConnected()) {
128                 try {
129                     ftpClient.disconnect();
130                 } catch (IOException ioe) {
131                 }
132             }
133         }
134         return success;
135     }
136     /**
137      * Description: 向FTP服务器新建文件夹
138      * @param ftpHost FTP服务器hostname
139      * @param ftpUserName 账号
140      * @param ftpPassword 密码
141      * @param ftpPort 端口
142      * @param ftpPath  FTP服务器中文件所在路径 格式: ftptest/aa
143      * @param fileName ftp文件名称
144      * @param input 文件流
145      * @return 成功返回true,否则返回false
146      */
147     public static boolean uploadFolder(String ftpPath,String fileName,FileManageRes ftpinfo) {
148         boolean success = false;
149         FTPClient ftpClient = null;
150         try {
151             int reply;
152             ftpClient = getFTPClient(ftpinfo);
153             reply = ftpClient.getReplyCode();
154             if (!FTPReply.isPositiveCompletion(reply)) {
155                 ftpClient.disconnect();
156                 return success;
157             }
158             ftpClient.setControlEncoding("UTF-8"); // 中文支持
159             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
160             ftpClient.enterLocalPassiveMode();
161             ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"),"iso-8859-1"));
162             ftpClient.makeDirectory(new String(fileName.getBytes("GBK"),"iso-8859-1"));
163             ftpClient.logout();
164             success = true;
165         } catch (IOException e) {
166             e.printStackTrace();
167         } finally {
168             if (ftpClient.isConnected()) {
169                 try {
170                     ftpClient.disconnect();
171                 } catch (IOException ioe) {
172                 }
173             }
174         }
175         return success;
176     }
177     /**
178      * Description: 重命名
179      * @param ftpHost FTP服务器hostname
180      * @param ftpUserName 账号
181      * @param ftpPassword 密码
182      * @param ftpPort 端口
183      * @param ftpPath  FTP服务器中文件所在路径 格式: ftptest/aa
184      * @param fileName ftp文件名称
185      * @param input 文件流
186      * @return 成功返回true,否则返回false
187      */
188     public static boolean renameFile(String ftpPath, String oldfileName,String newfileName,FileManageRes ftpinfo) {
189         boolean success = false;
190         FTPClient ftpClient = null;
191         try {
192             int reply;
193             ftpClient = getFTPClient(ftpinfo);
194             reply = ftpClient.getReplyCode();
195             if (!FTPReply.isPositiveCompletion(reply)) {
196                 ftpClient.disconnect();
197                 return success;
198             }
199             ftpClient.setControlEncoding("UTF-8"); // 中文支持
200             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
201             ftpClient.enterLocalPassiveMode();
202             ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"),"iso-8859-1"));
203             ftpClient.rename(new String(oldfileName.getBytes("GBK"),"iso-8859-1"),new String(newfileName.getBytes("GBK"),"iso-8859-1"));
204             ftpClient.logout();
205             success = true;
206         } catch (IOException e) {
207             e.printStackTrace();
208         } finally {
209             if (ftpClient.isConnected()) {
210                 try {
211                     ftpClient.disconnect();
212                 } catch (IOException ioe) {
213                 }
214             }
215         }
216         return success;
217     }
218     //TODO
219     public static  boolean downLoadFolder(String ftpPath, String localPath,String fileName,FileManageRes ftpinfo){
220         boolean flag = false;
221         FTPClient ftpClient = null;
222         String newfilename = null;
223         String folderpath = fileCreate(localPath + File.separatorChar + fileName);
224         try {
225             ftpClient = getFTPClient(ftpinfo);
226             ftpClient.setControlEncoding("GBK");
227             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
228             ftpClient.enterLocalPassiveMode();
229             ArrayList<String> pathArray=new ArrayList<String>();
230             if("".equals(ftpPath)){
231                 ftpClient.changeWorkingDirectory(new String(fileName.getBytes("GBK"),"iso-8859-1"));
232             }else{
233                 ftpClient.changeWorkingDirectory(new String((ftpPath+File.separatorChar+fileName).getBytes("GBK"),"iso-8859-1"));
234             }
235             getPath(ftpClient,fileName,pathArray,folderpath);
236             download(ftpClient, pathArray, folderpath);
237 //            if(ftpPath==null){
238 //                ftpClient.changeWorkingDirectory(new String(fileName.getBytes("GBK"),"iso-8859-1"));
239 //            }else{
240 //                ftpClient.changeWorkingDirectory(new String((ftpPath+File.separatorChar+fileName).getBytes("GBK"),"iso-8859-1"));
241 //            }
242 //                FTPFile[] files = ftpClient.listFiles();  
243 //                for(FTPFile file:files){  
244 //                    if(file.isFile()){  
245 //                        newfilename = file.getName();
246 //                         File localFile = new File(folderpath + File.separatorChar + newfilename);
247 //                         OutputStream os = new FileOutputStream(localFile);
248 //                         flag = ftpClient.retrieveFile(new String(newfilename.getBytes("GBK"),"iso-8859-1"), os);
249 //                         os.close();
250 //                         ftpClient.logout();
251 //                    }else if(file.isDirectory()){  
252 //                        newfilename = file.getName();
253 //                    }  
254 //            }  
255         } catch (FileNotFoundException e) {
256             System.out.println("没有找到" + ftpPath + "文件");
257             e.printStackTrace();
258         } catch (SocketException e) {
259             System.out.println("连接FTP失败.");
260             e.printStackTrace();
261         } catch (IOException e) {
262             e.printStackTrace();
263             System.out.println("文件读取错误。");
264             e.printStackTrace();
265         }
266         return flag;
267     }
268     public static void getPath(FTPClient ftp,String path,ArrayList<String> pathArray,String folderpath) throws IOException{
269         FTPFile[] files = ftp.listFiles();
270         for (FTPFile ftpFile : files) {
271             if(ftpFile.isFile()){
272                 if("".equals(path)){
273                     path+=ftpFile.getName();
274                 }else{
275                     path+="\\"+ftpFile.getName();
276                 }
277                 pathArray.add(path);
278             }
279             if(ftpFile.isDirectory()){//如果是目录,则递归调用,查找里面所有文件
280                 if("".equals(path)){
281                     path+=ftpFile.getName();
282                 }else{
283                     path+="\\"+ftpFile.getName();
284                 }
285                 folderpath=folderpath+"\\"+ftpFile.getName();
286                 fileCreate(folderpath);
287                 ftp.changeWorkingDirectory(new String(ftpFile.getName().getBytes("GBK"),"iso-8859-1"));//改变当前路径
288                 getPath(ftp,path,pathArray,folderpath);//递归调用
289                 //path=path.substring(0, path.lastIndexOf("/"));//避免对之后的同目录下的路径构造作出干扰,
290             }
291         }
292     }
293     public static void download(FTPClient ftp,ArrayList<String> pathArray,String localRootPath) throws IOException{
294         for (String string : pathArray) {
295             String localPath=localRootPath+string;
296             File localFile = new File(localPath);
297             if (!localFile.exists()) {  
298                 localFile.mkdirs();  
299             }
300         }
301         for (String string : pathArray) {
302             String localPath=localRootPath+string;//构造本地路径
303             ftp.changeWorkingDirectory(string);
304             FTPFile[] file=ftp.listFiles();
305             for (FTPFile ftpFile : file) {
306                 if(ftpFile.getName().equals(".")||ftpFile.getName().equals(".."))continue;
307                 File localFile = new File(localPath);
308                 if(!ftpFile.isDirectory()){
309                     OutputStream is = new FileOutputStream(localFile+"/"+ftpFile.getName());
310                     ftp.retrieveFile(ftpFile.getName(), is);
311                     is.close();
312                 }
313             }
314         }
315     }
316     /**
317      * 创建文件夹
318      * @param parentPath 父类路径
319      * @param fileDirName 创建文件夹的名称
320      * @return 返回创建文件夹的路径
321      */
322     public static String fileCreate(String parentPath){
323         String path=null;
324         File pFile=new File(parentPath);
325         if(!pFile.exists()){
326             pFile.mkdir();//如果父类不存在则新建
327         }
328         
329         path=pFile.getPath();//得到文件路径
330         //cFile.setWritable(true);//设置为可写操作        
331         return path;
332     } 
333 }

 

以上是关于FTPClient上传下载等的主要内容,如果未能解决你的问题,请参考以下文章

FtpClient

FtpClient上传文件速度非常慢,而且大小为0,上传失败

FTPClient下载文件0kb问题

使用Qt开发FTPClient的问题

FTP服务器文件上传的代码实现

FTPClient - Java,上传文件