JAVA中使用FTPClient工具类上传下载

Java程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件。本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。

1、写一个javabean文件,描述ftp上传或下载的信息

[java]  view plain  copy
  1. public class FtpUseBean {  
  2.     private String host;  
  3.     private Integer port;  
  4.     private String userName;  
  5.     private String password;  
  6.     private String ftpSeperator;  
  7.     private String ftpPath="";  
  8.     private int repeatTime = 0;//连接ftp服务器的次数  
  9.       
  10.     public String getHost() {  
  11.         return host;  
  12.     }  
  13.       
  14.     public void setHost(String host) {  
  15.         this.host = host;  
  16.     }  
  17.   
  18.     public Integer getPort() {  
  19.         return port;  
  20.     }  
  21.     public void setPort(Integer port) {  
  22.         this.port = port;  
  23.     }  
  24.       
  25.       
  26.     public String getUserName() {  
  27.         return userName;  
  28.     }  
  29.       
  30.     public void setUserName(String userName) {  
  31.         this.userName = userName;  
  32.     }  
  33.       
  34.     public String getPassword() {  
  35.         return password;  
  36.     }  
  37.       
  38.     public void setPassword(String password) {  
  39.         this.password = password;  
  40.     }  
  41.   
  42.     public void setFtpSeperator(String ftpSeperator) {  
  43.         this.ftpSeperator = ftpSeperator;  
  44.     }  
  45.   
  46.     public String getFtpSeperator() {  
  47.         return ftpSeperator;  
  48.     }  
  49.   
  50.     public void setFtpPath(String ftpPath) {  
  51.         if(ftpPath!=null)  
  52.             this.ftpPath = ftpPath;  
  53.     }  
  54.   
  55.     public String getFtpPath() {  
  56.         return ftpPath;  
  57.     }  
  58.   
  59.     public void setRepeatTime(int repeatTime) {  
  60.         if (repeatTime > 0)  
  61.             this.repeatTime = repeatTime;  
  62.     }  
  63.   
  64.     public int getRepeatTime() {  
  65.         return repeatTime;  
  66.     }  
  67.   
  68.     /** 
  69.      * take an example:<br> 
  70.      * ftp://userName:password@ip:port/ftpPath/ 
  71.      * @return  
  72.      */  
  73.     public String getFTPURL() {  
  74.         StringBuffer buf = new StringBuffer();  
  75.         buf.append("ftp://");  
  76.         buf.append(getUserName());  
  77.         buf.append(":");  
  78.         buf.append(getPassword());  
  79.         buf.append("@");  
  80.         buf.append(getHost());  
  81.         buf.append(":");  
  82.         buf.append(getPort());  
  83.         buf.append("/");  
  84.         buf.append(getFtpPath());  
  85.            
  86.         return buf.toString();  
  87.     }  
  88. }  
  89. 2、导入包commons-net-1.4.1.jar  
[java]  view plain  copy
  1. package com.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.DataOutputStream;  
  6. import java.io.File;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.io.OutputStream;  
  12. import java.net.SocketException;  
  13. import java.net.URL;  
  14. import java.net.URLConnection;  
  15.   
  16. import org.apache.commons.logging.Log;  
  17. import org.apache.commons.logging.LogFactory;  
  18. import org.apache.commons.net.ftp.FTP;  
  19. import org.apache.commons.net.ftp.FTPClient;  
  20. import org.apache.commons.net.ftp.FTPClientConfig;  
  21. import org.apache.commons.net.ftp.FTPFile;  
  22.   
  23. import com.bean.FtpUseBean;  
  24.   
  25. public class FtpUtil extends FTPClient {  
  26.   
  27.     private static Log log = LogFactory.getLog(FtpUtil.class);  
  28.     private FtpUseBean ftpUseBean;  
  29.     //获取目标路径下的文件属性信息,主要是获取文件的size  
  30.     private FTPFile[] files;  
  31.           
  32.     public FtpUseBean getFtpUseBean() {  
  33.         return ftpUseBean;  
  34.     }  
  35.   
  36.   
  37.     public FtpUtil(){  
  38.         super();  
  39.     }  
  40.       
  41.       
  42.     public void setFtpUseBean(FtpUseBean ftpUseBean) {  
  43.         this.ftpUseBean = ftpUseBean;  
  44.     }  
  45.       
  46.     public boolean ftpLogin() {  
  47.         boolean isLogined = false;  
  48.         try {  
  49.             log.debug("ftp login start ...");  
  50.             int repeatTime = ftpUseBean.getRepeatTime();  
  51.             for (int i = 0; i < repeatTime; i++) {  
  52.                 super.connect(ftpUseBean.getHost(), ftpUseBean.getPort());  
  53.                 isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword());  
  54.                 if (isLogined)  
  55.                     break;  
  56.             }  
  57.             if(isLogined)  
  58.                 log.debug("ftp login successfully ...");  
  59.             else  
  60.                 log.debug("ftp login failed ...");  
  61.             return isLogined;  
  62.         } catch (SocketException e) {  
  63.             log.error("", e);  
  64.             return false;  
  65.         } catch (IOException e) {  
  66.             log.error("", e);  
  67.             return false;  
  68.         } catch (RuntimeException e) {  
  69.             log.error("", e);  
  70.             return false;  
  71.         }  
  72.     }  
  73.   
  74.     public void setFtpToUtf8() throws IOException {  
  75.   
  76.         FTPClientConfig conf = new FTPClientConfig();  
  77.         super.configure(conf);  
  78.         super.setFileType(FTP.IMAGE_FILE_TYPE);  
  79.         int reply = super.sendCommand("OPTS UTF8 ON");  
  80.         if (reply == 200) { // UTF8 Command  
  81.             super.setControlEncoding("UTF-8");  
  82.         }  
  83.   
  84.     }  
  85.   
  86.     public void close() {  
  87.         if (super.isConnected()) {  
  88.             try {  
  89.                 super.logout();  
  90.                 super.disconnect();  
  91.                 log.debug("ftp logout ....");  
  92.             } catch (Exception e) {  
  93.                 log.error(e.getMessage());  
  94.                 throw new RuntimeException(e.toString());  
  95.             }  
  96.         }  
  97.     }  
  98.   
  99.     public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException {  
  100.         super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream);  
  101.     }  
  102.   
  103.     public File downFtpFile(String fileName, String localFileName) throws IOException {  
  104.         File outfile = new File(localFileName);  
  105.         OutputStream oStream = null;  
  106.         try {  
  107.             oStream = new FileOutputStream(outfile);  
  108.             super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream);  
  109.             return outfile;  
  110.         } finally {  
  111.             if (oStream != null)  
  112.                 oStream.close();  
  113.         }  
  114.     }  
  115.   
  116.   
  117.     public FTPFile[] listFtpFiles() throws IOException {  
  118.         return super.listFiles(ftpUseBean.getFtpPath());  
  119.     }  
  120.   
  121.     public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException {  
  122.         String path = ftpUseBean.getFtpPath();  
  123.         for (FTPFile ff : ftpFiles) {  
  124.             if (ff.isFile()) {  
  125.                 if (!super.deleteFile(path + ff.getName()))  
  126.                     throw new RuntimeException("delete File" + ff.getName() + " is n't seccess");  
  127.             }  
  128.         }  
  129.     }  
  130.   
  131.     public void deleteFtpFile(String fileName) throws IOException {  
  132.         if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName))  
  133.             throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess");  
  134.     }  
  135.   
  136.     public InputStream downFtpFile(String fileName) throws IOException {  
  137.         return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName);  
  138.     }  
  139.   
  140.     /** 
  141.      *  
  142.      * @return 
  143.      * @return StringBuffer 
  144.      * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL 
  145.      */  
  146.     public StringBuffer downloadBufferByURL(String addr) {  
  147.         BufferedReader in = null;  
  148.         try {  
  149.             URL url = new URL(addr);  
  150.             URLConnection conn = url.openConnection();  
  151.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  152.             String line;  
  153.             StringBuffer ret = new StringBuffer();  
  154.             while ((line = in.readLine()) != null)  
  155.                 ret.append(line);  
  156.               
  157.             return ret;  
  158.         } catch (Exception e) {  
  159.             log.error(e);  
  160.             return null;  
  161.         } finally {  
  162.             try {  
  163.                 if (null != in)  
  164.                     in.close();  
  165.             } catch (IOException e) {  
  166.                 e.printStackTrace();  
  167.                 log.error(e);  
  168.             }  
  169.         }  
  170.     }  
  171.   
  172.     /** 
  173.      *  
  174.      * @return 
  175.      * @return byte[] 
  176.      * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL 
  177.      */  
  178.     public byte[] downloadByteByURL(String addr) {  
  179.           
  180.         FTPClient ftp = null;  
  181.           
  182.         try {  
  183.               
  184.             URL url = new URL(addr);  
  185.               
  186.             int port = url.getPort()!=-1?url.getPort():21;  
  187.             log.info("HOST:"+url.getHost());  
  188.             log.info("Port:"+port);  
  189.             log.info("USERINFO:"+url.getUserInfo());  
  190.             log.info("PATH:"+url.getPath());  
  191.               
  192.             ftp = new FTPClient();  
  193.               
  194.             ftp.setDataTimeout(30000);  
  195.             ftp.setDefaultTimeout(30000);  
  196.             ftp.setReaderThread(false);  
  197.             ftp.connect(url.getHost(), port);  
  198.             ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);  
  199.             FTPClientConfig conf = new FTPClientConfig("UNIX");     
  200.                       ftp.configure(conf);   
  201.             log.info(ftp.getReplyString());  
  202.               
  203.             ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()   
  204.             ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);   
  205.   
  206.             int reply = ftp.sendCommand("OPTS UTF8 ON");// try to  
  207.               
  208.             log.debug("alter to utf-8 encoding - reply:" + reply);  
  209.             if (reply == 200) { // UTF8 Command  
  210.                 ftp.setControlEncoding("UTF-8");  
  211.             }  
  212.             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
  213.   
  214.             log.info(ftp.getReplyString());  
  215.               
  216.             ByteArrayOutputStream out=new ByteArrayOutputStream();  
  217.                       DataOutputStream o=new DataOutputStream(out);  
  218.                       String remotePath = url.getPath();  
  219.                       /** 
  220.                       * Fixed:if doen't remove the first "/" at the head of url, 
  221.                        * the file can't be retrieved. 
  222.                       */  
  223.                      if(remotePath.indexOf("/")==0) {  
  224.                           remotePath = url.getPath().replaceFirst("/""");  
  225.                      }  
  226.                      ftp.retrieveFile(remotePath, o);             
  227.             byte[] ret = out.toByteArray();  
  228.             o.close();  
  229.               
  230.             String filepath = url.getPath();  
  231.             ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/")));  
  232.             files = ftp.listFiles();  
  233.               
  234.             return ret;  
  235.                } catch (Exception ex) {  
  236.             log.error("Failed to download file from ["+addr+"]!"+ex);  
  237.               } finally {  
  238.             try {  
  239.                 if (null!=ftp)  
  240.                     ftp.disconnect();  
  241.             } catch (Exception e) {  
  242.                 //  
  243.             }  
  244.         }  
  245.         return null;  
  246. //      StringBuffer buffer = downloadBufferByURL(addr);  
  247. //      return null == buffer ? null : buffer.toString().getBytes();  
  248.     }  
  249.       
  250.       
  251.       
  252.       
  253.     public FTPFile[] getFiles() {  
  254.         return files;  
  255.     }  
  256.   
  257.   
  258.     public void setFiles(FTPFile[] files) {  
  259.         this.files = files;  
  260.     }  
  261.   
  262.   
  263. //  public static void getftpfilesize(String addr){  
  264. //        
  265. //      FTPClient ftp = null;  
  266. //        
  267. //      try {  
  268. //            
  269. //          URL url = new URL(addr);  
  270. //            
  271. //          int port = url.getPort()!=-1?url.getPort():21;  
  272. //          log.info("HOST:"+url.getHost());  
  273. //          log.info("Port:"+port);  
  274. //          log.info("USERINFO:"+url.getUserInfo());  
  275. //          log.info("PATH:"+url.getPath());  
  276. //            
  277. //          ftp = new FTPClient();  
  278. //            
  279. //          ftp.setDataTimeout(30000);  
  280. //          ftp.setDefaultTimeout(30000);  
  281. //          ftp.setReaderThread(false);  
  282. //          ftp.connect(url.getHost(), port);  
  283. //          ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);  
  284. //          FTPClientConfig conf = new FTPClientConfig("UNIX");     
  285. //          ftp.configure(conf);   
  286. //          log.info(ftp.getReplyString());  
  287. //            
  288. //          ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()   
  289. //          ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);   
  290. //  
  291. //          int reply = ftp.sendCommand("OPTS UTF8 ON");// try to  
  292. //            
  293. //          log.debug("alter to utf-8 encoding - reply:" + reply);  
  294. //          if (reply == 200) { // UTF8 Command  
  295. //              ftp.setControlEncoding("UTF-8");  
  296. //          }  
  297. //          ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
  298. //          ftp.changeWorkingDirectory(url.getPath());  
  299. //          FTPFile[] files = ftp.listFiles();  
  300. //          for (FTPFile flie : files){  
  301. //              System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1"));  
  302. //              System.out.println(flie.getSize());  
  303. //          }  
  304. //            
  305. //  
  306. //      } catch (Exception ex) {  
  307. //          log.error("Failed to download file from ["+addr+"]!"+ex);  
  308. //      } finally {  
  309. //          try {<pre class="java" name="code">         if (null!=ftp)  
  310. //          ftp.disconnect();  
  311.  //          } catch (Exception e) {  
  312. }  
  313. }  
  314. }  
  315. }</pre>  
  316. <pre></pre>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值