最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解JAVA中使用FTPClient工具類上傳下載

 更新時間:2017年08月02日 14:24:02   作者:快樂的燕子會飛  
這篇文章主要介紹了JAVA中使用FTPClient工具類上傳下載的相關(guān)資料,java 使用FTP服務(wù)器上傳文件、下載文件,需要的朋友可以參考下

詳解JAVA中使用FTPClient工具類上傳下載

在Java程序中,經(jīng)常需要和FTP打交道,比如向FTP服務(wù)器上傳文件、下載文件。本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現(xiàn)上傳下載文件。

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服務(wù)器的次數(shù) 
   
  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、導(dǎo)入包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; 
  //獲取目標(biāo)路徑下的文件屬性信息,主要是獲取文件的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服務(wù)器上的文件,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服務(wù)器上的文件,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工具類的上傳和下載的實例詳解,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

  • Spring boot webService使用方法解析

    Spring boot webService使用方法解析

    這篇文章主要介紹了Spring boot webService使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-09-09
  • IDEA 2020.1.2 安裝教程附破解教程詳解

    IDEA 2020.1.2 安裝教程附破解教程詳解

    這篇文章主要介紹了IDEA 2020.1.2 安裝教程附帶破解教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • 使用Springboot+Vue實現(xiàn)文件上傳和下載功能

    使用Springboot+Vue實現(xiàn)文件上傳和下載功能

    本文介紹了如何使用Springboot結(jié)合Vue進(jìn)行圖書信息管理系統(tǒng)開發(fā),包括數(shù)據(jù)庫表的創(chuàng)建,實體類、Dao層、Service層和Controller層的編寫,重點講解了文件上傳和下載功能的實現(xiàn),感興趣的朋友跟隨小編一起看看吧
    2024-09-09
  • Java編程中的條件判斷之if語句的用法詳解

    Java編程中的條件判斷之if語句的用法詳解

    這篇文章主要介紹了Java編程中的條件判斷之if語句的用法詳解,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-11-11
  • Spring根據(jù)URL參數(shù)進(jìn)行路由的方法詳解

    Spring根據(jù)URL參數(shù)進(jìn)行路由的方法詳解

    這篇文章主要給大家介紹了關(guān)于Spring根據(jù)URL參數(shù)進(jìn)行路由的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起來看看吧。
    2017-12-12
  • Java中String、StringBuffer和StringBuilder的區(qū)別與使用場景

    Java中String、StringBuffer和StringBuilder的區(qū)別與使用場景

    在Java編程中,String、StringBuffer和StringBuilder是用于處理字符串的常見類,它們在可變性、線程安全性和性能方面有所不同,具有一定的參考價值,感興趣的可以了解一下
    2024-05-05
  • Linux 下通過 java 命令啟動 jar 包常見方式小結(jié)

    Linux 下通過 java 命令啟動 jar 包常見方式小結(jié)

    這篇文章主要介紹了Linux 下通過 java 命令啟動 jar 包常見方式小結(jié),后臺啟動jar包命令大致有五種,每種方式結(jié)合代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧
    2023-12-12
  • java編程幾行代碼實現(xiàn)買菜自由

    java編程幾行代碼實現(xiàn)買菜自由

    這篇文章主要為大家介紹了java編程幾行代碼實現(xiàn)買菜自由,需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • Java中16條的代碼規(guī)范

    Java中16條的代碼規(guī)范

    如何更規(guī)范化編寫Java 代碼的重要性想必毋需多言,其中最重要的幾點當(dāng)屬提高代碼性能、使代碼遠(yuǎn)離Bug、令代碼更優(yōu)雅,
    2021-07-07
  • java中List接口的方法詳解

    java中List接口的方法詳解

    這篇文章主要介紹了java中List接口的方法詳解,List接口是繼承Collection接口,所以Collection集合中有的方法,List集合也繼承過來,本文主要介紹一下list下的方法,需要的朋友可以參考下
    2023-10-10

最新評論

靖安县| 南陵县| 台东县| 永嘉县| 淳安县| 沛县| 宁海县| 美姑县| 香港 | 大余县| 怀仁县| 高青县| 垣曲县| 祁连县| 星座| 呈贡县| 浏阳市| 镇巴县| 永康市| 沙湾县| 泌阳县| 墨竹工卡县| 乐清市| 广东省| 本溪| 凤台县| 淮滨县| 罗定市| 乐山市| 阿巴嘎旗| 周至县| 视频| 伽师县| 牡丹江市| 雅江县| 盘山县| 安泽县| 安达市| 天门市| 宜川县| 扎囊县|