java is based on Apache FTP points for intermittent file upload and download

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

To implement the file upload and download tool based on Apache FTP, the following issues should be considered when uploading files (example is the continuation function) :

(1) does the FTP server have a modified directory? If it does not, a directory needs to be created.

(2) determine whether the uploaded file already exists, and if so, upload it after deleting it or upload it again.

1. Enumeration class of upload or download status:


package com.scengine.wtms.utils.ftp; 
 
public enum UploadStatus 
{ 
  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_locall(12); 
 
  private int status; 
 
  public int getStatus() 
  { 
    return status; 
  } 
 
  public void setStatus(int status) 
  { 
    this.status = status; 
  } 
 
  UploadStatus(int status) 
  { 
    this.status = status; 
  } 
} 

2. 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 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; 
 
public class ContinueFTP 
{ 
 
  private FTPClient ftpClient = new FTPClient(); 
 
  /** 
   *  Object construction   Sets the output of the commands used in the process to the console  
   */ 
  public ContinueFTP() 
  { 
    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; 
 
  } 
 
  /** 
   * 
   *  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 boolean download(String remote, String local) throws IOException 
  { 
 
    ftpClient.enterLocalPassiveMode(); 
 
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
 
    boolean result; 
 
    File f = new File(local); 
 
    FTPFile[] files = ftpClient.listFiles(remote); 
 
    if (files.length != 1) 
    { 
      System.out.println(" Remote files are not unique 1"); 
      return false; 
    } 
 
    long lRemoteSize = files[0].getSize(); 
 
    if (f.exists()) 
    { 
      OutputStream out = new FileOutputStream(f, true); 
      System.out.println(" The local file size is :" + f.length()); 
 
      if (f.length() >= lRemoteSize) 
      { 
 
        System.out.println(" Local file size is larger than remote file size, download aborts "); 
 
        return false; 
 
      } 
 
      ftpClient.setRestartOffset(f.length()); 
 
      result = ftpClient.retrieveFile(remote, out); 
 
      out.close(); 
 
    } else 
    { 
 
      OutputStream out = new FileOutputStream(f); 
      result = ftpClient.retrieveFile(remote, out); 
      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 UploadStatus 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); 
 
    UploadStatus 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 
            { 
 
              System.out.println(" Directory creation failed "); 
 
              return UploadStatus.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 UploadStatus.File_Exits; 
 
      } else if (remoteSize > localSize) 
      { 
 
        return UploadStatus.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 UploadStatus.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 UploadStatus.Delete_Remote_Faild; 
 
      } 
 
      is = new FileInputStream(f); 
 
      if (ftpClient.storeFile(remote, is)) 
      { 
 
        result = UploadStatus.Upload_New_File_Success; 
 
      } else 
      { 
 
        result = UploadStatus.Upload_New_File_Failed; 
 
      } 
 
      is.close(); 
 
    } else 
    { 
 
      InputStream is = new FileInputStream(local); 
 
      if (ftpClient.storeFile(remoteFileName, is)) 
      { 
 
        result = UploadStatus.Upload_New_File_Success; 
 
      } else 
      { 
 
        result = UploadStatus.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) 
  { 
    ContinueFTP myFtp = new ContinueFTP(); 
    try 
    { 
 
      myFtp.connect("192.168.1.200", 21, "duser", "HTPDuserXP32"); 
 
      System.out.println(myFtp.upload("C:\\Users\\Administrator\\Desktop\\swing.drawer.jar", "/jars/swing.drawer.jar")); 
 
      myFtp.disconnect(); 
 
    } catch (IOException e) 
    { 
 
      System.out.println(" The connection FTP Error: " + e.getMessage()); 
 
    } 
 
  } 
 
} 

Related articles: