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

 更新时间:2017年08月02日 14:24:02   作者:快乐的燕子会飞  
这篇文章主要介绍了JAVA中使用FTPClient工具类上传下载的相关资料,java 使用FTP服务器上传文件、下载文件,需要的朋友可以参考下

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

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

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

实例代码:

public class FtpUseBean { 
  private String host; 
  private Integer port; 
  private String userName; 
  private String password; 
  private String ftpSeperator; 
  private String ftpPath=""; 
  private int repeatTime = 0;//连接ftp服务器的次数 
   
  public String getHost() { 
    return host; 
  } 
   
  public void setHost(String host) { 
    this.host = host; 
  } 
 
  public Integer getPort() { 
    return port; 
  } 
  public void setPort(Integer port) { 
    this.port = port; 
  } 
   
   
  public String getUserName() { 
    return userName; 
  } 
   
  public void setUserName(String userName) { 
    this.userName = userName; 
  } 
   
  public String getPassword() { 
    return password; 
  } 
   
  public void setPassword(String password) { 
    this.password = password; 
  } 
 
  public void setFtpSeperator(String ftpSeperator) { 
    this.ftpSeperator = ftpSeperator; 
  } 
 
  public String getFtpSeperator() { 
    return ftpSeperator; 
  } 
 
  public void setFtpPath(String ftpPath) { 
    if(ftpPath!=null) 
      this.ftpPath = ftpPath; 
  } 
 
  public String getFtpPath() { 
    return ftpPath; 
  } 
 
  public void setRepeatTime(int repeatTime) { 
    if (repeatTime > 0) 
      this.repeatTime = repeatTime; 
  } 
 
  public int getRepeatTime() { 
    return repeatTime; 
  } 
 
  /** 
   * take an example:<br> 
   * ftp://userName:password@ip:port/ftpPath/ 
   * @return 
   */ 
  public String getFTPURL() { 
    StringBuffer buf = new StringBuffer(); 
    buf.append("ftp://"); 
    buf.append(getUserName()); 
    buf.append(":"); 
    buf.append(getPassword()); 
    buf.append("@"); 
    buf.append(getHost()); 
    buf.append(":"); 
    buf.append(getPort()); 
    buf.append("/"); 
    buf.append(getFtpPath()); 
      
    return buf.toString(); 
  } 
} 

2、导入包commons-net-1.4.1.jar 

package com.util; 
 
import java.io.BufferedReader; 
import java.io.ByteArrayOutputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.SocketException; 
import java.net.URL; 
import java.net.URLConnection; 
 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPClientConfig; 
import org.apache.commons.net.ftp.FTPFile; 
 
import com.bean.FtpUseBean; 
 
public class FtpUtil extends FTPClient { 
 
  private static Log log = LogFactory.getLog(FtpUtil.class); 
  private FtpUseBean ftpUseBean; 
  //获取目标路径下的文件属性信息,主要是获取文件的size 
  private FTPFile[] files; 
     
  public FtpUseBean getFtpUseBean() { 
    return ftpUseBean; 
  } 
 
 
  public FtpUtil(){ 
    super(); 
  } 
   
   
  public void setFtpUseBean(FtpUseBean ftpUseBean) { 
    this.ftpUseBean = ftpUseBean; 
  } 
   
  public boolean ftpLogin() { 
    boolean isLogined = false; 
    try { 
      log.debug("ftp login start ..."); 
      int repeatTime = ftpUseBean.getRepeatTime(); 
      for (int i = 0; i < repeatTime; i++) { 
        super.connect(ftpUseBean.getHost(), ftpUseBean.getPort()); 
        isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword()); 
        if (isLogined) 
          break; 
      } 
      if(isLogined) 
        log.debug("ftp login successfully ..."); 
      else 
        log.debug("ftp login failed ..."); 
      return isLogined; 
    } catch (SocketException e) { 
      log.error("", e); 
      return false; 
    } catch (IOException e) { 
      log.error("", e); 
      return false; 
    } catch (RuntimeException e) { 
      log.error("", e); 
      return false; 
    } 
  } 
 
  public void setFtpToUtf8() throws IOException { 
 
    FTPClientConfig conf = new FTPClientConfig(); 
    super.configure(conf); 
    super.setFileType(FTP.IMAGE_FILE_TYPE); 
    int reply = super.sendCommand("OPTS UTF8 ON"); 
    if (reply == 200) { // UTF8 Command 
      super.setControlEncoding("UTF-8"); 
    } 
 
  } 
 
  public void close() { 
    if (super.isConnected()) { 
      try { 
        super.logout(); 
        super.disconnect(); 
        log.debug("ftp logout ...."); 
      } catch (Exception e) { 
        log.error(e.getMessage()); 
        throw new RuntimeException(e.toString()); 
      } 
    } 
  } 
 
  public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException { 
    super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream); 
  } 
 
  public File downFtpFile(String fileName, String localFileName) throws IOException { 
    File outfile = new File(localFileName); 
    OutputStream oStream = null; 
    try { 
      oStream = new FileOutputStream(outfile); 
      super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream); 
      return outfile; 
    } finally { 
      if (oStream != null) 
        oStream.close(); 
    } 
  } 
 
 
  public FTPFile[] listFtpFiles() throws IOException { 
    return super.listFiles(ftpUseBean.getFtpPath()); 
  } 
 
  public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException { 
    String path = ftpUseBean.getFtpPath(); 
    for (FTPFile ff : ftpFiles) { 
      if (ff.isFile()) { 
        if (!super.deleteFile(path + ff.getName())) 
          throw new RuntimeException("delete File" + ff.getName() + " is n't seccess"); 
      } 
    } 
  } 
 
  public void deleteFtpFile(String fileName) throws IOException { 
    if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName)) 
      throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess"); 
  } 
 
  public InputStream downFtpFile(String fileName) throws IOException { 
    return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName); 
  } 
 
  /** 
   * 
   * @return 
   * @return StringBuffer 
   * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL 
   */ 
  public StringBuffer downloadBufferByURL(String addr) { 
    BufferedReader in = null; 
    try { 
      URL url = new URL(addr); 
      URLConnection conn = url.openConnection(); 
      in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String line; 
      StringBuffer ret = new StringBuffer(); 
      while ((line = in.readLine()) != null) 
        ret.append(line); 
       
      return ret; 
    } catch (Exception e) { 
      log.error(e); 
      return null; 
    } finally { 
      try { 
        if (null != in) 
          in.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
        log.error(e); 
      } 
    } 
  } 
 
  /** 
   * 
   * @return 
   * @return byte[] 
   * @description 下载ftp服务器上的文件,addr为带用户名和密码的URL 
   */ 
  public byte[] downloadByteByURL(String addr) { 
     
    FTPClient ftp = null; 
     
    try { 
       
      URL url = new URL(addr); 
       
      int port = url.getPort()!=-1?url.getPort():21; 
      log.info("HOST:"+url.getHost()); 
      log.info("Port:"+port); 
      log.info("USERINFO:"+url.getUserInfo()); 
      log.info("PATH:"+url.getPath()); 
       
      ftp = new FTPClient(); 
       
      ftp.setDataTimeout(30000); 
      ftp.setDefaultTimeout(30000); 
      ftp.setReaderThread(false); 
      ftp.connect(url.getHost(), port); 
      ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]); 
      FTPClientConfig conf = new FTPClientConfig("UNIX");   
           ftp.configure(conf);  
      log.info(ftp.getReplyString()); 
       
      ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()  
      ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
 
      int reply = ftp.sendCommand("OPTS UTF8 ON");// try to 
       
      log.debug("alter to utf-8 encoding - reply:" + reply); 
      if (reply == 200) { // UTF8 Command 
        ftp.setControlEncoding("UTF-8"); 
      } 
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
 
      log.info(ftp.getReplyString()); 
       
      ByteArrayOutputStream out=new ByteArrayOutputStream(); 
           DataOutputStream o=new DataOutputStream(out); 
           String remotePath = url.getPath(); 
           /** 
           * Fixed:if doen't remove the first "/" at the head of url, 
            * the file can't be retrieved. 
           */ 
           if(remotePath.indexOf("/")==0) { 
             remotePath = url.getPath().replaceFirst("/", ""); 
           } 
           ftp.retrieveFile(remotePath, o);       
      byte[] ret = out.toByteArray(); 
      o.close(); 
       
      String filepath = url.getPath(); 
      ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/"))); 
      files = ftp.listFiles(); 
       
      return ret; 
        } catch (Exception ex) { 
      log.error("Failed to download file from ["+addr+"]!"+ex); 
       } finally { 
      try { 
        if (null!=ftp) 
          ftp.disconnect(); 
      } catch (Exception e) { 
        // 
      } 
    } 
    return null; 
//   StringBuffer buffer = downloadBufferByURL(addr); 
//   return null == buffer ? null : buffer.toString().getBytes(); 
  } 
   
   
   
   
  public FTPFile[] getFiles() { 
    return files; 
  } 
 
 
  public void setFiles(FTPFile[] files) { 
    this.files = files; 
  } 
 
 
// public static void getftpfilesize(String addr){ 
//    
//   FTPClient ftp = null; 
//    
//   try { 
//      
//     URL url = new URL(addr); 
//      
//     int port = url.getPort()!=-1?url.getPort():21; 
//     log.info("HOST:"+url.getHost()); 
//     log.info("Port:"+port); 
//     log.info("USERINFO:"+url.getUserInfo()); 
//     log.info("PATH:"+url.getPath()); 
//      
//     ftp = new FTPClient(); 
//      
//     ftp.setDataTimeout(30000); 
//     ftp.setDefaultTimeout(30000); 
//     ftp.setReaderThread(false); 
//     ftp.connect(url.getHost(), port); 
//     ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]); 
//     FTPClientConfig conf = new FTPClientConfig("UNIX");   
//     ftp.configure(conf);  
//     log.info(ftp.getReplyString()); 
//      
//     ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()  
//     ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
// 
//     int reply = ftp.sendCommand("OPTS UTF8 ON");// try to 
//      
//     log.debug("alter to utf-8 encoding - reply:" + reply); 
//     if (reply == 200) { // UTF8 Command 
//       ftp.setControlEncoding("UTF-8"); 
//     } 
//     ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
//     ftp.changeWorkingDirectory(url.getPath()); 
//     FTPFile[] files = ftp.listFiles(); 
//     for (FTPFile flie : files){ 
//       System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1")); 
//       System.out.println(flie.getSize()); 
//     } 
//      
// 
//   } catch (Exception ex) { 
//     log.error("Failed to download file from ["+addr+"]!"+ex); 
//   } finally { 
//     try {<pre class="java" name="code">     if (null!=ftp) 
//     ftp.disconnect(); 
 //     } catch (Exception e) { 
} 
} 
} 
}

以上就是JAVA FTPClient工具类的上传和下载的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

  • Mybatis-Plus中getOne方法获取最新一条数据的示例代码

    Mybatis-Plus中getOne方法获取最新一条数据的示例代码

    这篇文章主要介绍了Mybatis-Plus中getOne方法获取最新一条数据,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • 简单了解springboot eureka交流机制

    简单了解springboot eureka交流机制

    这篇文章主要介绍了简单了解springboot eureka交流机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • spring通过构造函数注入实现方法分析

    spring通过构造函数注入实现方法分析

    这篇文章主要介绍了spring通过构造函数注入实现方法,结合实例形式分析了spring通过构造函数注入的原理、实现步骤及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • idea中maven本地仓库jar包打包失败和无法引用的问题解决

    idea中maven本地仓库jar包打包失败和无法引用的问题解决

    本文主要介绍了idea中maven本地仓库jar包打包失败和无法引用的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • java操作mongodb实现CURD功能实例

    java操作mongodb实现CURD功能实例

    mongodb支持多种语言,并且提供了多种语言的驱动,本文使用java操作mongodb实现CURD功能,大家参考使用吧
    2013-12-12
  • SpringBoot使用Caffeine实现缓存的示例代码

    SpringBoot使用Caffeine实现缓存的示例代码

    本文主要介绍了SpringBoot使用Caffeine实现缓存的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 手把手带你用java搞定汉诺塔

    手把手带你用java搞定汉诺塔

    这篇文章主要给大家介绍了关于Java青蛙跳台阶问题的解决思路与代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • 一文搞懂Spring中@Autowired和@Resource的区别

    一文搞懂Spring中@Autowired和@Resource的区别

    @Autowired 和 @Resource 都是 Spring/Spring Boot 项目中,用来进行依赖注入的注解。它们都提供了将依赖对象注入到当前对象的功能,但二者却有众多不同,并且这也是常见的面试题之一,所以我们今天就来盘它
    2022-08-08
  • struts2静态资源映射代码示例

    struts2静态资源映射代码示例

    这篇文章主要介绍了struts2静态资源映射的相关内容,涉及了具体代码示例,具有一定参考价值,需要的朋友可以了解下。
    2017-09-09
  • 在Intellij Idea中使用jstl标签库的方法

    在Intellij Idea中使用jstl标签库的方法

    这篇文章主要介绍了在Intellij Idea中使用jstl标签库的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05

最新评论