lsdwyl 发表于 2015-5-28 09:54:54

Java 利用Apache Commons Net 实现 FTP文件上传下载

  Java 利用Apache Commons Net 实现 FTP文件上传下载 [转]



1 package woxingwosu;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.text.SimpleDateFormat;
9 import java.util.Comparator;
10 import java.util.Properties;
11 import java.util.TreeSet;
12 import org.apache.commons.io.FileUtils;
13 import org.apache.commons.net.ftp.FTP;
14 import org.apache.commons.net.ftp.FTPClient;
15 import org.apache.commons.net.ftp.FTPClientConfig;
16 import org.apache.commons.net.ftp.FTPFile;
17 import org.apache.commons.net.ftp.FTPReply;
18
19 /**
20 * 其实JDK里面也有支持FTP操作的包【jre/lib下的rt.jar】,但是SUN的DOC里面并没有提供相应文档,
21 * 因为这里面的包,不被官方支持,建议不要使用。我们可以使用第三方提供的包apache.commons。
22 * apache.commons的包,都有文档,方便使用
23 * 另外IBM也有提供一个ftp包,我没有用过,有兴趣的可以去研究一下
24 * @commons-net:http://apache.mirror.phpchina.com/commons/net/binaries/commons-net-1.4.1.zip
25 * @jakarta-oro:http://mirror.vmmatrix.net/apache/jakarta/oro/source/jakarta-oro-2.0.8.zip
26 * @commons-io:http://apache.mirror.phpchina.com/commons/io/binaries/commons-io-1.3.2-bin.zip
27 * @author 我行我素
28 * @2007-08-03
29 */
30 public class MiniFtp {
31   private static String username;
32   private static String password;
33   private static String ip;
34   private static int port;
35   private static Properties property=null;//配置
36   private static String configFile;//配置文件的路径名
37   
38   private static FTPClient ftpClient=null;
39   private static SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm");
40   
41   private static final String [] FILE_TYPES={"文件","目录","符号链接","未知类型"};
42   
43   public static void main(String[] args) {
44          setConfigFile("woxingwosu.properties");//设置配置文件路径
45          connectServer();
46          listAllRemoteFiles();//列出所有文件和目录
47          changeWorkingDirectory("webroot");//进入文件夹webroot
48          listRemoteFiles("*.jsp");//列出webroot目录下所有jsp文件
49          setFileType(FTP.BINARY_FILE_TYPE);//设置传输二进制文件
50          uploadFile("woxingwosu.xml","myfile.xml");//上传文件woxingwosu.xml,重新命名为myfile.xml
51          renameFile("viewDetail.jsp", "newName.jsp");//将文件viewDetail.jsp改名为newName.jsp
52          deleteFile("UpdateData.class");//删除文件UpdateData.class
53          loadFile("UpdateData.java","loadFile.java");//下载文件UpdateData.java,并且重新命名为loadFile.java
54          closeConnect();//关闭连接
55      }
56   
57   /**
58       * 上传文件
59       * @param localFilePath--本地文件路径
60       * @param newFileName--新的文件名
61      */
62   public static void uploadFile(String localFilePath,String newFileName){
63          connectServer();
64         //上传文件
65          BufferedInputStream buffIn=null;
66         try{
67            buffIn=new BufferedInputStream(new FileInputStream(localFilePath));
68            ftpClient.storeFile(newFileName, buffIn);
69          }catch(Exception e){
70            e.printStackTrace();
71          }finally{
72             try{
73               if(buffIn!=null)
74                      buffIn.close();
75            }catch(Exception e){
76                  e.printStackTrace();
77            }
78          }
79      }
80   
81   /**
82       * 下载文件
83       * @param remoteFileName --服务器上的文件名
84       * @param localFileName--本地文件名
85      */
86   public static void loadFile(String remoteFileName,String localFileName){
87          connectServer();
88         //下载文件
89          BufferedOutputStream buffOut=null;
90         try{
91            buffOut=new BufferedOutputStream(new FileOutputStream(localFileName));
92            ftpClient.retrieveFile(remoteFileName, buffOut);
93          }catch(Exception e){
94            e.printStackTrace();
95          }finally{
96             try{
97               if(buffOut!=null)
98                      buffOut.close();
99            }catch(Exception e){
100                  e.printStackTrace();
101            }
102          }
103      }
104   
105   /**
106       * 列出服务器上所有文件及目录
107      */
108   public static void listAllRemoteFiles(){
109          listRemoteFiles("*");
110      }
111
112   /**
113       * 列出服务器上文件和目录
114       * @param regStr --匹配的正则表达式
115      */
116      @SuppressWarnings("unchecked")
117   public static void listRemoteFiles(String regStr){
118          connectServer();
119         try{
120            FTPFile[] files=ftpClient.listFiles(regStr);
121             if(files==null||files.length==0)
122                  System.out.println("There has not any file!");
123             else{
124                  TreeSet fileTree=new TreeSet(
125                         new Comparator(){
126                           //先按照文件的类型排序(倒排),然后按文件名顺序排序
127                           public int compare(Object objFile1,Object objFile2){
128                                 if(objFile1==null)
129                                     return -1;
130                                 else if(objFile2==null)
131                                     return 1;
132                                 else{
133                                    FTPFile file1=(FTPFile)objFile1;
134                                    FTPFile file2=(FTPFile)objFile2;
135                                     if(file1.getType()!=file2.getType())
136                                       return file2.getType()-file1.getType();
137                                     else
138                                       return file1.getName().compareTo(file2.getName());
139                                  }
140                              }
141                        }
142                  );
143               for(FTPFile file:files)
144                      fileTree.add(file);
145                  System.out.printf("%-35s%-10s%15s%15s\n","名称","类型","修改日期","大小");
146               for(FTPFile file:fileTree){
147                      System.out.printf("%-35s%-10s%15s%15s\n",iso8859togbk(file.getName()),FILE_TYPES
148                              ,dateFormat.format(file.getTimestamp().getTime()),FileUtils.byteCountToDisplaySize(file.getSize()));
149                  }
150            }
151          }catch(Exception e){
152            e.printStackTrace();
153          }
154      }
155   
156   /**
157       * 关闭连接
158      */
159   public static void closeConnect(){
160         try{
161             if(ftpClient!=null){
162                  ftpClient.logout();
163                  ftpClient.disconnect();
164            }
165          }catch(Exception e){
166            e.printStackTrace();
167          }
168      }
169   
170   /**
171       * 设置配置文件
172       * @param configFile
173      */
174   public static void setConfigFile(String configFile) {
175          MiniFtp.configFile = configFile;
176      }
177   
178   /**
179       * 设置传输文件的类型[文本文件或者二进制文件]
180       * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
181      */
182   public static void setFileType(int fileType){
183         try{
184            connectServer();
185            ftpClient.setFileType(fileType);
186          }catch(Exception e){
187            e.printStackTrace();
188          }
189      }
190   
191   /**
192       * 扩展使用
193       * @return
194      */
195   protected static FTPClient getFtpClient(){
196          connectServer();
197         return ftpClient;
198      }
199
200   /**
201       * 设置参数
202       * @param configFile --参数的配置文件
203      */
204   private static void setArg(String configFile){
205          property=new Properties();
206          BufferedInputStream inBuff=null;
207         try{
208            inBuff=new BufferedInputStream(new FileInputStream(configFile));
209            property.load(inBuff);
210            username=property.getProperty("username");
211            password=property.getProperty("password");
212            ip=property.getProperty("ip");
213            port=Integer.parseInt(property.getProperty("port"));
214          }catch(Exception e){
215            e.printStackTrace();
216          }finally{
217             try{
218               if(inBuff!=null)
219                      inBuff.close();
220            }catch(Exception e){
221                  e.printStackTrace();
222            }
223          }
224      }
225   
226   /**
227       * 连接到服务器
228      */
229   public static void connectServer() {
230         if (ftpClient == null) {
231             int reply;
232             try {
233                  setArg(configFile);
234                  ftpClient=new FTPClient();
235                  ftpClient.setDefaultPort(port);
236                  ftpClient.configure(getFtpConfig());
237                  ftpClient.connect(ip);
238                  ftpClient.login(username, password);
239                  ftpClient.setDefaultPort(port);
240                  System.out.print(ftpClient.getReplyString());
241                  reply = ftpClient.getReplyCode();
242
243               if (!FTPReply.isPositiveCompletion(reply)) {
244                      ftpClient.disconnect();
245                      System.err.println("FTP server refused connection.");
246                  }
247            } catch (Exception e) {
248                  System.err.println("登录ftp服务器【"+ip+"】失败");
249                  e.printStackTrace();
250            }
251          }
252      }
253   
254   /**
255       * 进入到服务器的某个目录下
256       * @param directory
257      */
258   public static void changeWorkingDirectory(String directory){
259         try{
260            connectServer();
261            ftpClient.changeWorkingDirectory(directory);
262          }catch(IOException ioe){
263            ioe.printStackTrace();
264          }
265      }
266   
267   /**
268       * 返回到上一层目录
269      */
270   public static void changeToParentDirectory(){
271         try{
272            connectServer();
273            ftpClient.changeToParentDirectory();
274          }catch(IOException ioe){
275            ioe.printStackTrace();
276          }
277      }
278   
279   /**
280       * 删除文件
281      */
282   public static void deleteFile(String filename){
283         try{
284            connectServer();
285            ftpClient.deleteFile(filename);
286          }catch(IOException ioe){
287            ioe.printStackTrace();
288          }
289      }
290   
291   /**
292       * 重命名文件
293       * @param oldFileName --原文件名
294       * @param newFileName --新文件名
295      */
296   public static void renameFile(String oldFileName,String newFileName){
297         try{
298            connectServer();
299            ftpClient.rename(oldFileName, newFileName);
300          }catch(IOException ioe){
301            ioe.printStackTrace();
302          }
303      }
304   
305   /**
306       * 设置FTP客服端的配置--一般可以不设置
307       * @return
308      */
309   private static FTPClientConfig getFtpConfig(){
310          FTPClientConfig ftpConfig=new FTPClientConfig(FTPClientConfig.SYST_UNIX);
311          ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
312         return ftpConfig;
313      }
314   
315   /**
316       * 转码
317       *不同的平台需要不同的转码
318       * @param obj
319       * @return
320      */
321   private static String iso8859togbk(Object obj){
322         try{
323             if(obj==null)
324               return "";
325             else
326               return new String(obj.toString().getBytes("iso-8859-1"),"GBK");
327          }catch(Exception e){
328             return "";
329          }
330      }
331 }
  
页: [1]
查看完整版本: Java 利用Apache Commons Net 实现 FTP文件上传下载