java realizes file upload download modify file name and delete based on Apache FTP

  • 2020-05-12 02:45:09
  • OfStack

Apache FTP is a widely used FTP upload client tool, which is easy to operate, simple code, clear structure, is a priority for FTP file client management software. The operations of FTP include: FTP file upload (continuation), FTP file download, FTP file rename, FTP file delete. These operations have already brought FTP's application management mode into full play. So has always used this mode to realize the management of FTP file server. The FTP tool code is attached below.

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(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 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(); 
 
  /** 
   *  Object construction   Sets the output of the commands used in the process to the console  
   */ 
  public FTPUtils() 
  { 
    this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); 
  } 
 
  /** 
   * 
   * java Used in programming to connect to FTP The server  
   * 
   * @param hostname 
   *       The host name  
   * 
   * @param port 
   *       port  
   * 
   * @param username 
   *       The user name  
   * 
   * @param password 
   *       password  
   * 
   * @return  Is the connection successful?  
   * 
   * @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; 
 
  } 
 
  /** 
   *  Delete the remote FTP file  
   * 
   * @param remote 
   *       Remote file path  
   * @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 Server file deletion identifier: "+result); 
    return result; 
  } 
   
  /** 
   *  Rename remote FTP file  
   * 
   * @param name 
   *       Name of the new remote file ( The path - We must ensure the same 1 Under the path ) 
   *       
   * @param remote 
   *       Remote file path  
   *       
   * @return  The success of  
   * 
   * @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 Server file name update id: "+result); 
    return result; 
  } 
   
  /** 
   * 
   *  from FTP Download the file on the server  
   * 
   * @param fileName 
   *       Download the name of the file ( Including suffixes ) 
   * 
   * @param remote 
   *       Remote file path  
   * 
   * @param local 
   *       Local file path  
   * 
   * @return  The success of  
   * 
   * @throws IOException 
   */ 
 
  public FTPStatus download(String fileName,String remote,HttpServletResponse response) throws IOException 
  { 
    //  Opens the save path selection window for the output stream  
    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 Server file download id: "+result); 
     
    out.close(); 
     
    return result; 
  } 
 
  /** 
   * 
   *  from FTP Download the file on the server  
   * 
   * @param remote 
   *       Remote file path  
   * 
   * @param local 
   *       Local file path  
   * 
   * @return  The success of  
   * 
   * @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(" Remote files are not unique 1"); 
      return FTPStatus.File_Not_Unique; 
    } 
 
    long lRemoteSize = files[0].getSize(); 
 
    if (f.exists()) 
    { 
      OutputStream out = new FileOutputStream(f, true); 
      Log.getLogger(this.getClass()).info(" The local file size is :" + f.length()); 
 
      if (f.length() >= lRemoteSize) 
      { 
 
        Log.getLogger(this.getClass()).info(" Local file size is larger than remote file size, download aborts "); 
        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 
   *       Local file name, absolute path  
   * 
   * @param remote 
   *       Remote file path, using /home/directory1/subdirectory/file.ext 
   *       In accordance with the Linux Support multiple levels of directory nesting, recursive creation of a directory structure that does not exist  
   * 
   * @return  Upload the result  
   * 
   * @throws IOException 
   */ 
 
  @SuppressWarnings("resource") 
  public FTPStatus upload(String local, String remote) throws IOException 
  { 
    //  Set up the PassiveMode transmission  
    ftpClient.enterLocalPassiveMode(); 
 
    //  Settings to 2 Base stream transmission  
    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 directory does not exist, the remote server directory is created recursively  
 
        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(" Directory creation failed "); 
 
              return FTPStatus.Create_Directory_Fail; 
 
            } 
 
          } 
 
          start = end + 1; 
 
          end = directory.indexOf("/", start); 
 
          //  Check that all directories are created  
 
          if (end <= start) 
          { 
 
            break; 
 
          } 
 
        } 
 
      } 
 
    } 
 
    //  Check to see if the remote file exists  
 
    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 inside the file , Realize breakpoint continuation  
 
      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 relay does not succeed, the file on the server is deleted and re-uploaded  
 
      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 the 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", 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 Abnormal upload file: " + e.getMessage()); 
 
    } 
 
  } 
 
} 

Related articles: