apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出

用到了apache 的 commons-net-3.0.1.jar 和 log4j-1.2.15.jar 这连个jar包

JAVA 代码如下:

  1 package com.bjut.edu.cn.ftp;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileNotFoundException;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.util.TimeZone;
 11 import org.apache.commons.net.ftp.FTPClient;
 12 import org.apache.commons.net.ftp.FTPClientConfig;
 13 import org.apache.commons.net.ftp.FTPFile;
 14 import org.apache.commons.net.ftp.FTPReply;
 15 
 16 import org.apache.log4j.Logger;
 17 
 18 public class Ftp {
 19     private FTPClient ftpClient;
 20     private String strIp;
 21     private int intPort;
 22     private String user;
 23     private String password;
 24 
 25     private static Logger logger = Logger.getLogger(Ftp.class.getName());
 26 
 27     /* *
 28      * Ftp构造函数
 29      */
 30     public Ftp(String strIp, int intPort, String user, String Password) {
 31         this.strIp = strIp;
 32         this.intPort = intPort;
 33         this.user = user;
 34         this.password = Password;
 35         this.ftpClient = new FTPClient();
 36     }
 37     /**
 38      * @return 判断是否登入成功
 39      * */
 40     public boolean ftpLogin() {
 41         boolean isLogin = false;
 42         FTPClientConfig ftpClientConfig = new FTPClientConfig();
 43         ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
 44         this.ftpClient.setControlEncoding("GBK");
 45         this.ftpClient.configure(ftpClientConfig);
 46         try {
 47             if (this.intPort > 0) {
 48                 this.ftpClient.connect(this.strIp, this.intPort);
 49             } else {
 50                 this.ftpClient.connect(this.strIp);
 51             }
 52             // FTP服务器连接回答
 53             int reply = this.ftpClient.getReplyCode();
 54             if (!FTPReply.isPositiveCompletion(reply)) {
 55                 this.ftpClient.disconnect();
 56                 logger.error("登录FTP服务失败!");
 57                 return isLogin;
 58             }
 59             this.ftpClient.login(this.user, this.password);
 60             // 设置传输协议
 61             this.ftpClient.enterLocalPassiveMode();
 62             this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
 63             logger.info("恭喜" + this.user + "成功登陆FTP服务器");
 64             isLogin = true;
 65         } catch (Exception e) {
 66             e.printStackTrace();
 67             logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
 68         }
 69         this.ftpClient.setBufferSize(1024 * 2);
 70         this.ftpClient.setDataTimeout(30 * 1000);
 71         return isLogin;
 72     }
 73 
 74     /**
 75      * @退出关闭服务器链接
 76      * */
 77     public void ftpLogOut() {
 78         if (null != this.ftpClient && this.ftpClient.isConnected()) {
 79             try {
 80                 boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
 81                 if (reuslt) {
 82                     logger.info("成功退出服务器");
 83                 }
 84             } catch (IOException e) {
 85                 e.printStackTrace();
 86                 logger.warn("退出FTP服务器异常!" + e.getMessage());
 87             } finally {
 88                 try {
 89                     this.ftpClient.disconnect();// 关闭FTP服务器的连接
 90                 } catch (IOException e) {
 91                     e.printStackTrace();
 92                     logger.warn("关闭FTP服务器的连接异常!");
 93                 }
 94             }
 95         }
 96     }
 97 
 98     /***
 99      * 上传Ftp文件
100      * @param localFile 当地文件
101      * @param romotUpLoadePath上传服务器路径 - 应该以/结束
102      * */
103     public boolean uploadFile(File localFile, String romotUpLoadePath) {
104         BufferedInputStream inStream = null;
105         boolean success = false;
106         try {
107             this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
108             inStream = new BufferedInputStream(new FileInputStream(localFile));
109             logger.info(localFile.getName() + "开始上传.....");
110             success = this.ftpClient.storeFile(localFile.getName(), inStream);
111             if (success == true) {
112                 logger.info(localFile.getName() + "上传成功");
113                 return success;
114             }
115         } catch (FileNotFoundException e) {
116             e.printStackTrace();
117             logger.error(localFile + "未找到");
118         } catch (IOException e) {
119             e.printStackTrace();
120         } finally {
121             if (inStream != null) {
122                 try {
123                     inStream.close();
124                 } catch (IOException e) {
125                     e.printStackTrace();
126                 }
127             }
128         }
129         return success;
130     }
131 
132     /***
133      * 下载文件
134      * @param remoteFileName   待下载文件名称
135      * @param localDires 下载到当地那个路径下
136      * @param remoteDownLoadPath remoteFileName所在的路径
137      * */
138 
139     public boolean downloadFile(String remoteFileName, String localDires,
140             String remoteDownLoadPath) {
141         String strFilePath = localDires + remoteFileName;
142         BufferedOutputStream outStream = null;
143         boolean success = false;
144         try {
145             this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
146             outStream = new BufferedOutputStream(new FileOutputStream(
147                     strFilePath));
148             logger.info(remoteFileName + "开始下载....");
149             success = this.ftpClient.retrieveFile(remoteFileName, outStream);
150             if (success == true) {
151                 logger.info(remoteFileName + "成功下载到" + strFilePath);
152                 return success;
153             }
154         } catch (Exception e) {
155             e.printStackTrace();
156             logger.error(remoteFileName + "下载失败");
157         } finally {
158             if (null != outStream) {
159                 try {
160                     outStream.flush();
161                     outStream.close();
162                 } catch (IOException e) {
163                     e.printStackTrace();
164                 }
165             }
166         }
167         if (success == false) {
168             logger.error(remoteFileName + "下载失败!!!");
169         }
170         return success;
171     }
172 
173     /***
174      * @上传文件夹
175      * @param localDirectory
176      *            当地文件夹
177      * @param remoteDirectoryPath
178      *            Ftp 服务器路径 以目录"/"结束
179      * */
180     public boolean uploadDirectory(String localDirectory,
181             String remoteDirectoryPath) {
182         File src = new File(localDirectory);
183         try {
184             remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
185             this.ftpClient.makeDirectory(remoteDirectoryPath);
186             // ftpClient.listDirectories();
187         } catch (IOException e) {
188             e.printStackTrace();
189             logger.info(remoteDirectoryPath + "目录创建失败");
190         }
191         File[] allFile = src.listFiles();
192         for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
193             if (!allFile[currentFile].isDirectory()) {
194                 String srcName = allFile[currentFile].getPath().toString();
195                 uploadFile(new File(srcName), remoteDirectoryPath);
196             }
197         }
198         for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
199             if (allFile[currentFile].isDirectory()) {
200                 // 递归
201                 uploadDirectory(allFile[currentFile].getPath().toString(),
202                         remoteDirectoryPath);
203             }
204         }
205         return true;
206     }
207 
208     /***
209      * @下载文件夹
210      * @param localDirectoryPath本地地址
211      * @param remoteDirectory 远程文件夹
212      * */
213     public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
214         try {
215             String fileName = new File(remoteDirectory).getName();
216             localDirectoryPath = localDirectoryPath + fileName + "//";
217             new File(localDirectoryPath).mkdirs();
218             FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
219             for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
220                 if (!allFile[currentFile].isDirectory()) {
221                     downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
222                 }
223             }
224             for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
225                 if (allFile[currentFile].isDirectory()) {
226                     String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
227                     downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
228                 }
229             }
230         } catch (IOException e) {
231             e.printStackTrace();
232             logger.info("下载文件夹失败");
233             return false;
234         }
235         return true;
236     }
237     // FtpClient的Set 和 Get 函数
238     public FTPClient getFtpClient() {
239         return ftpClient;
240     }
241     public void setFtpClient(FTPClient ftpClient) {
242         this.ftpClient = ftpClient;
243     }
244     
245     public static void main(String[] args) throws IOException {
246         Ftp ftp=new Ftp("10.3.15.1",21,"ghips","ghipsteam");
247         ftp.ftpLogin();
248         //上传文件夹
249         ftp.uploadDirectory("d://DataProtemp", "/home/data/");
250         //下载文件夹
251         ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
252         ftp.ftpLogOut();        
253     }
254 }