Java based on Apache FTP implementation file upload, download, modify file name, delete _java

Source: Internet
Author: User
Tags create directory file upload ftp file ftp upload file

Apache FTP is a more extensive application of FTP upload client tools, it is easy to operate, code simple, clear structure, is to do FTP file client management software priority. FTP operations include: FTP file Upload (breakpoint continued), FTP file downloads, ftp file renaming, FTP file deletion, these operations have been the FTP application management way to play incisively and vividly, so I have always used this way to achieve the management of FTP file server ; The FTP tool code is attached.

1, FTP file operation State Enumeration class

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 (a), Remote_Bigger_ Local (one), remote_smaller_local (Not_exist_file), remote_rename_success (), Remote_rename_faild, File_ Not_unique (); 
 
  private int status; 
 
  public int GetStatus () 
  {return 
    status; 
  } 
 
  public void setstatus (int status) 
  { 
    this.status = status; 
  } 
 
  Ftpstatus (int status) 
  { 
    this.status = status; 
  } 
} 

2, FTP file Operation tool Code

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 (); The/** * Object construction setting outputs the commands used in the procedure to the console/public ftputils () {This.ftpClient.addProtocolCommandListener (new Prin 
  Tcommandlistener (New PrintWriter (System.out));  
   /** * * * * java Programming for connecting to FTP server * * @param hostname * Host name * * @param port * * @param username * User name * * @paramPassword * Password * * @return Whether the connection succeeded * * @throws IOException/public boolean connect (Strin 
 
    g 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; /** * Delete Remote FTP file * * @param remote file path * @return * @throws IOException/P 
 
    Ublic 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 Server file deletion identity:" +result); 
  return result; 
   /** * Rename remote FTP file * * @param name * NEW remote filename (path-must be guaranteed under the same path) * * @param remote * Remote File path * * @return Success * * @throws IOException/Public ftpstatus rename (String na 
 
    Me,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 server filename Update ID:" +result); 
  return result; }/** * * from FTP Clothing* * @param filename * Download file name (including suffix name) * * @param remote file path * * @par AM local * Path * * @return Success * * @throws ioexception/public ftpstatus Download ( String filename,string remote,httpservletresponse response) throws IOException {//Open output bullet out File Save path Selection window Respons 
     
    E.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 server file Download ID:" +result);  
    Out.close (); 
  return result;  
   /** * * Download files from FTP server * * @param remote file path * * @param local file path * * @return Success * * @throws IOException/@SuppressWarnings ("resource") public ftpstatus do 
 
    Wnload (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 ("Remote file is not unique"); 
    return ftpstatus.file_not_unique; 
 
    Long lremotesize = Files[0].getsize (); 
      if (f.exists ()) {OutputStream out = new FileOutputStream (f, true); 
 
      Log.getlogger (This.getclass ()). info ("Local File size is:" + f.length ()); if (F.length () >= lremotesize) {Log.getlogger (This.getclass ()). info ("Local file size larger than remote file size, download aborted"); 
 
      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;      /** * * * * Upload files to FTP server, support breakpoint Continuation * * @param local * name, absolute path * * @param remote * Remote file path, using/home/directory1/subdirectory/file.ext * According to the path specified on Linux, support multilevel directory nesting, support recursively create nonexistent directory structure * * @retur N Upload Results * * @throws IOException/@SuppressWarnings ("resource") public ftpstatus upload (String local, 
String remote) throws IOException {    Set Passivemode transmission Ftpclient.enterlocalpassivemode (); 
 
    A binary stream is set to transmit Ftpclient.setfiletype (ftp.binary_file_type); 
 
    Ftpstatus result; 
 
    Processing of remote directories 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)) {//If the remote eye 
 
        Record does not exist, then recursively creates the remote server 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 ("Create directory Failed"); 
 
            return ftpstatus.create_directory_fail; 
 
          } start = end + 1; 
 
          End = Directory.indexof ("/", start); 
 
          Check that all directories are created if (end <= start) {break; 
 
    Check whether there is a remote file 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; //Try to move the read pointer within the file to implementThe breakpoint continues to pass 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 the breakpoint is not successful, delete the file on the server and upload 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;  
  /** * * Disconnect from remote server * * @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", "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 Upload file exception:" + E.getmessage ()); 
 } 
 
  } 
 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.