java基於Apache FTP實現檔案上傳、下載、修改檔案名稱、刪除_java

來源:互聯網
上載者:User

Apache FTP 是應用比較廣泛的FTP上傳用戶端工具,它易於操作,代碼簡略,結構清晰,是做FTP檔案用戶端管理軟體的優先之選。FTP的操作包括:FTP檔案上傳(斷點續傳)、FTP檔案下載、FTP檔案重新命名、FTP檔案刪除,這些操作已經將FTP應用管理的方式發揮的淋漓盡致了,So 我一直都用此種方式來實現FTP檔案伺服器的管理工作;下附FTP工具代碼。

1、FTP檔案操作狀態枚舉類

package com.scengine.wtms.utils.ftp;  public enum FTPStatus {   File_Exits(0), Create_Directory_Success(1), Create_Directory_Fail(2), Upload_From_Break_Success(3), Upload_From_Break_Faild(4), Download_From_Break_Success(5), Download_From_Break_Faild(6), Upload_New_File_Success(7), Upload_New_File_Failed(8), Delete_Remote_Success(9), Delete_Remote_Faild(10),Remote_Bigger_Local(11),Remote_smaller_local(12),Not_Exist_File(13),Remote_Rename_Success(14),Remote_Rename_Faild(15),File_Not_Unique(16);    private int status;    public int getStatus()   {     return status;   }    public void setStatus(int status)   {     this.status = status;   }    FTPStatus(int status)   {     this.status = status;   } } 

2、FTP檔案操作工具代碼

package com.scengine.wtms.utils.ftp;  import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.scengine.wtms.utils.Log;  public class FTPUtils {   private FTPClient ftpClient = new FTPClient();    /**    * 物件建構 設定將過程中使用到的命令輸出到控制台    */   public FTPUtils()   {     this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));   }    /**    *    * java編程中用於串連到FTP伺服器    *    * @param hostname    *      主機名稱    *    * @param port    *      連接埠    *    * @param username    *      使用者名稱    *    * @param password    *      密碼    *    * @return 是否串連成功    *    * @throws IOException    */    public boolean connect(String hostname, int port, String username, String password) throws IOException   {      ftpClient.connect(hostname, port);      if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))     {        if (ftpClient.login(username, password))       {         return true;       }     }     disconnect();     return false;    }    /**    * 刪除遠程FTP檔案    *    * @param remote    *      遠程檔案路徑    * @return    * @throws IOException    */   public FTPStatus delete(String remote) throws IOException   {     ftpClient.enterLocalPassiveMode();      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);      FTPStatus result = null;      FTPFile[] files = ftpClient.listFiles(remote);     if (files.length == 1)     {       boolean status = ftpClient.deleteFile(remote);       result = status ? FTPStatus.Delete_Remote_Success : FTPStatus.Delete_Remote_Faild;     }     else     {       result = FTPStatus.Not_Exist_File;     }     Log.getLogger(this.getClass()).info("FTP伺服器檔案刪除標識:"+result);     return result;   }      /**    * 重新命名遠程FTP檔案    *    * @param name    *      新遠程檔案名稱(路徑-必須保證在同一路徑下)    *          * @param remote    *      遠程檔案路徑    *          * @return 是否成功    *    * @throws IOException    */   public FTPStatus rename(String name,String remote) throws IOException   {     ftpClient.enterLocalPassiveMode();      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);      FTPStatus result = null;      FTPFile[] files = ftpClient.listFiles(remote);     if (files.length == 1)     {       boolean status = ftpClient.rename(remote, name);       result = status ? FTPStatus.Remote_Rename_Success : FTPStatus.Remote_Rename_Faild;     }     else     {       result = FTPStatus.Not_Exist_File;     }     Log.getLogger(this.getClass()).info("FTP伺服器檔案名稱更新標識:"+result);     return result;   }      /**    *    * 從FTP伺服器上下載檔案    *    * @param fileName    *      下載檔案的名字(包括尾碼名)    *    * @param remote    *      遠程檔案路徑    *    * @param local    *      本地檔案路徑    *    * @return 是否成功    *    * @throws IOException    */    public FTPStatus download(String fileName,String remote,HttpServletResponse response) throws IOException   {     // 開啟輸出資料流彈出檔案儲存直接選取視窗     response.setContentType("application/octet-stream");          response.setContentType("application/OCTET-STREAM;charset=UTF-8");          response.setHeader("Content-Disposition", "attachment;filename=" +fileName);      ftpClient.enterLocalPassiveMode();      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);          FTPStatus result;          OutputStream out = response.getOutputStream();          boolean status = ftpClient.retrieveFile(remote, out);          result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;          Log.getLogger(this.getClass()).info("FTP伺服器檔案下載標識:"+result);          out.close();          return result;   }    /**    *    * 從FTP伺服器上下載檔案    *    * @param remote    *      遠程檔案路徑    *    * @param local    *      本地檔案路徑    *    * @return 是否成功    *    * @throws IOException    */    @SuppressWarnings("resource")   public FTPStatus download(String remote, String local) throws IOException   {      ftpClient.enterLocalPassiveMode();      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);      FTPStatus result;      File f = new File(local);      FTPFile[] files = ftpClient.listFiles(remote);      if (files.length != 1)     {       Log.getLogger(this.getClass()).info("遠程檔案不唯一");       return FTPStatus.File_Not_Unique;     }      long lRemoteSize = files[0].getSize();      if (f.exists())     {       OutputStream out = new FileOutputStream(f, true);       Log.getLogger(this.getClass()).info("本地檔案大小為:" + f.length());        if (f.length() >= lRemoteSize)       {          Log.getLogger(this.getClass()).info("本地檔案大小大於遠程檔案大小,下載中止");         return FTPStatus.Remote_smaller_local;        }        ftpClient.setRestartOffset(f.length());        boolean status = ftpClient.retrieveFile(remote, out);       result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;       out.close();      } else     {       OutputStream out = new FileOutputStream(f);       boolean status = ftpClient.retrieveFile(remote, out);       result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;       out.close();     }      return result;    }    /**    *    * 上傳檔案到FTP伺服器,支援斷點續傳    *    * @param local    *      本地檔案名稱,絕對路徑    *    * @param remote    *      遠程檔案路徑,使用/home/directory1/subdirectory/file.ext    *      按照Linux上的路徑指定方式,支援多級目錄嵌套,支援遞迴建立不存在的目錄結構    *    * @return 上傳結果    *    * @throws IOException    */    @SuppressWarnings("resource")   public FTPStatus upload(String local, String remote) throws IOException   {     // 設定PassiveMode傳輸     ftpClient.enterLocalPassiveMode();      // 設定以二進位流的方式傳輸     ftpClient.setFileType(FTP.BINARY_FILE_TYPE);      FTPStatus result;      // 對遠程目錄的處理     String remoteFileName = remote;      if (remote.contains("/"))     {        remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);        if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory))       {          // 如果遠程目錄不存在,則遞迴建立遠程伺服器目錄          int start = 0;          int end = 0;          if (directory.startsWith("/"))         {            start = 1;          } else         {            start = 0;          }          end = directory.indexOf("/", start);          while (true)         {            String subDirectory = remote.substring(start, end);            if (!ftpClient.changeWorkingDirectory(subDirectory))           {              if (ftpClient.makeDirectory(subDirectory))             {                ftpClient.changeWorkingDirectory(subDirectory);              } else             {                Log.getLogger(this.getClass()).info("建立目錄失敗");                return FTPStatus.Create_Directory_Fail;              }            }            start = end + 1;            end = directory.indexOf("/", start);            // 檢查所有目錄是否建立完畢            if (end <= start)           {              break;            }          }        }      }      // 檢查遠程是否存在檔案      FTPFile[] files = ftpClient.listFiles(remoteFileName);      if (files.length == 1)     {        long remoteSize = files[0].getSize();        File f = new File(local);        long localSize = f.length();        if (remoteSize == localSize)       {          return FTPStatus.File_Exits;        } else if (remoteSize > localSize)       {          return FTPStatus.Remote_Bigger_Local;        }        // 嘗試移動檔案內讀取指標,實現斷點續傳        InputStream is = new FileInputStream(f);        if (is.skip(remoteSize) == remoteSize)       {          ftpClient.setRestartOffset(remoteSize);          if (ftpClient.storeFile(remote, is))         {            return FTPStatus.Upload_From_Break_Success;          }        }        // 如果斷點續傳沒有成功,則刪除伺服器上檔案,重新上傳        if (!ftpClient.deleteFile(remoteFileName))       {          return FTPStatus.Delete_Remote_Faild;        }        is = new FileInputStream(f);        if (ftpClient.storeFile(remote, is))       {          result = FTPStatus.Upload_New_File_Success;        } else       {          result = FTPStatus.Upload_New_File_Failed;        }        is.close();      } else     {        InputStream is = new FileInputStream(local);        if (ftpClient.storeFile(remoteFileName, is))       {          result = FTPStatus.Upload_New_File_Success;        } else       {          result = FTPStatus.Upload_New_File_Failed;        }        is.close();     }      return result;    }    /**    *    * 斷開與遠程伺服器的串連    *    * @throws IOException    */    public void disconnect() throws IOException   {      if (ftpClient.isConnected())     {       ftpClient.disconnect();     }    }    public static void main(String[] args)   {     FTPUtils myFtp = new FTPUtils();     try     {        myFtp.connect("192.168.1.200", 21, "duser", "HTPDuserXP32");        Log.getLogger(FTPUtils.class).info(myFtp.upload("C:\\Users\\Administrator\\Desktop\\swing.drawer.jar", "/jars/swing.drawer.jar"));        myFtp.disconnect();      } catch (IOException e)     {        Log.getLogger(FTPUtils.class).info("FTP上傳檔案異常:" + e.getMessage());      }    }  } 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.