Java implements the upload and download of FTP files and folders

  • 2020-05-26 08:26:04
  • OfStack

FTP is short for File Transfer Protocol (file transfer protocol) in English, but short for "text transfer protocol" in Chinese. For two-way transfer of control files on Internet. It is also an application (Application). There are different FTP applications based on different operating systems, and all of these applications adhere to the same protocol to transfer files. In the use of FTP, users often encounter two concepts: "download" (Download) and "upload" (Upload). To download "a file is to copy a file from a remote host to your own computer." To upload a file is to copy it from your own computer to a remote host. In Internet, users can upload (download) files to (from) a remote host via a client program.

First of all, I downloaded Serv-U and set up my computer as FTP file server for easy operation. The following code is used after the FTP server has been created, and only after the FTP connection data has been written in the code can it be completed.

1. Upload and download FTP files (note: upload and download a single file)


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;
/**
 *  implementation FTP File upload and file download 
 */
public class FtpApche {
 private static FTPClient ftpClient = new FTPClient();
 private static String encoding = System.getProperty("file.encoding");
 /**
  * Description:  to FTP Server upload file 
  * 
  * @Version1.0
  * @param url
  *   FTP The server hostname
  * @param port
  *   FTP Server port 
  * @param username
  *   FTP Login account 
  * @param password
  *   FTP The login password 
  * @param path
  *   FTP Server save directory , If it's the root directory, it's" / " 
  * @param filename
  *    Uploaded to the FTP The file name on the server 
  * @param input
  *    Local file input stream 
  * @return  Successfully returns true Otherwise return false
  */
 public static boolean uploadFile(String url, int port, String username,
   String password, String path, String filename, InputStream input) {
  boolean result = false;
  try {
   int reply;
   //  If the default port is used, it can be used ftp.connect(url) The way of direct connection FTP The server 
   ftpClient.connect(url);
   // ftp.connect(url, port);//  The connection FTP The server 
   //  The login 
   ftpClient.login(username, password);
   ftpClient.setControlEncoding(encoding);
   //  Verify that the connection was successful 
   reply = ftpClient.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    System.out.println(" The connection fails ");
    ftpClient.disconnect();
    return result;
   }
   //  Transfer the working directory to the specified directory 
   boolean change = ftpClient.changeWorkingDirectory(path);
   ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
   if (change) {
    result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
    if (result) {
     System.out.println(" Uploaded successfully !");
    }
   }
   input.close();
   ftpClient.logout();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return result;
 }
 /**
  *  Upload the local file to FTP On the server 
  * 
  */
 public void testUpLoadFromDisk() {
  try {
   FileInputStream in = new FileInputStream(new File("D:/test02/list.txt"));
   boolean flag = uploadFile("10.0.0.102", 21, "admin","123456", "/", "lis.txt", in);
   System.out.println(flag);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }
 /**
  * Description:  from FTP Server download file 
  * 
  * @Version1.0
  * @param url
  *   FTP The server hostname
  * @param port
  *   FTP Server port 
  * @param username
  *   FTP Login account 
  * @param password
  *   FTP The login password 
  * @param remotePath
  *   FTP The relative path on the server 
  * @param fileName
  *    The file name to download 
  * @param localPath
  *    Save to the local path after downloading 
  * @return
  */
 public static boolean downFile(String url, int port, String username,
   String password, String remotePath, String fileName,
   String localPath) {
  boolean result = false;
  try {
   int reply;
   ftpClient.setControlEncoding(encoding);
   /*
    *  In order to upload and download Chinese files, some places suggest using the following two sentences instead 
    * new String(remotePath.getBytes(encoding),"iso-8859-1") Transcoding. 
    *  After testing, it didn't pass. 
    */
//   FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//   conf.setServerLanguageCode("zh");
   ftpClient.connect(url, port);
   //  If the default port is used, it can be used ftp.connect(url) The way of direct connection FTP The server 
   ftpClient.login(username, password);//  The login 
   //  Set the file transfer type to 2 Into the system 
   ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   //  To obtain ftp Login reply code 
   reply = ftpClient.getReplyCode();
   //  Verify that the login was successful 
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
    System.err.println("FTP server refused connection.");
    return result;
   }
   //  Transferred to the FTP Server directory to the specified directory 
   ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
   //  Get a list of files 
   FTPFile[] fs = ftpClient.listFiles();
   for (FTPFile ff : fs) {
    if (ff.getName().equals(fileName)) {
     File localFile = new File(localPath + "/" + ff.getName());
     OutputStream is = new FileOutputStream(localFile);
     ftpClient.retrieveFile(ff.getName(), is);
     is.close();
    }
   }
   ftpClient.logout();
   result = true;
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return result;
 }
 /**
  *  will FTP The file on the server is downloaded locally 
  * 
  */
 public void testDownFile() {
  try {
   boolean flag = downFile("10.0.0.102", 21, "admin",
     "123456", "/", "ip.txt", "E:/");
   System.out.println(flag);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public static void main(String[] args) {
  FtpApche fa = new FtpApche();
  fa.testDownFile();
  fa.testUpLoadFromDisk();
 }
}

2. Upload and download the FTP folder (note the entire folder)


package ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
public class FTPTest_04 {
 private FTPClient ftpClient;
 private String strIp;
 private int intPort;
 private String user;
 private String password;
 private static Logger logger = Logger.getLogger(FTPTest_04.class.getName());
 /* * 
  * Ftp The constructor  
  */ 
 public FTPTest_04(String strIp, int intPort, String user, String Password) {
  this.strIp = strIp;
  this.intPort = intPort;
  this.user = user;
  this.password = Password;
  this.ftpClient = new FTPClient();
 }
 /** 
  * @return  Determine whether the login was successful  
  * */ 
 public boolean ftpLogin() {
  boolean isLogin = false;
  FTPClientConfig ftpClientConfig = new FTPClientConfig();
  ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
  this.ftpClient.setControlEncoding("GBK");
  this.ftpClient.configure(ftpClientConfig);
  try {
   if (this.intPort > 0) {
    this.ftpClient.connect(this.strIp, this.intPort);
   }else {
    this.ftpClient.connect(this.strIp);
   }
   // FTP Server connection answer  
   int reply = this.ftpClient.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    this.ftpClient.disconnect();
    logger.error(" The login FTP Service failed! ");
    return isLogin;
   }
   this.ftpClient.login(this.user, this.password);
   //  Set transport protocol  
   this.ftpClient.enterLocalPassiveMode();
   this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   logger.info(" congratulations " + this.user + " Success of landing FTP The server ");
   isLogin = true;
  }catch (Exception e) {
   e.printStackTrace();
   logger.error(this.user + " The login FTP Service failed! " + e.getMessage());
  }
  this.ftpClient.setBufferSize(1024 * 2);
  this.ftpClient.setDataTimeout(30 * 1000);
  return isLogin;
 }
 /** 
  * @ Exit close server link  
  * */ 
 public void ftpLogOut() {
  if (null != this.ftpClient && this.ftpClient.isConnected()) {
   try {
    boolean reuslt = this.ftpClient.logout();//  exit FTP The server  
    if (reuslt) {
     logger.info(" Exit the server successfully ");
    }
   }catch (IOException e) {
    e.printStackTrace();
    logger.warn(" exit FTP Server exception! " + e.getMessage());
   }finally {
    try {
     this.ftpClient.disconnect();//  Shut down FTP Server connection  
    }catch (IOException e) {
     e.printStackTrace();
     logger.warn(" Shut down FTP Server connection is abnormal! ");
    }
   }
  }
 }
 /*** 
  *  upload Ftp file  
  * @param localFile  Local file  
  * @param romotUpLoadePath Upload server path  -  Should be to / The end of the  
  * */ 
 public boolean uploadFile(File localFile, String romotUpLoadePath) {
  BufferedInputStream inStream = null;
  boolean success = false;
  try {
   this.ftpClient.changeWorkingDirectory(romotUpLoadePath);//  Change work path  
   inStream = new BufferedInputStream(new FileInputStream(localFile));
   logger.info(localFile.getName() + " To upload .....");
   success = this.ftpClient.storeFile(localFile.getName(), inStream);
   if (success == true) {
    logger.info(localFile.getName() + " Uploaded successfully ");
    return success;
   }
  }catch (FileNotFoundException e) {
   e.printStackTrace();
   logger.error(localFile + " Not found ");
  }catch (IOException e) {
   e.printStackTrace();
  }finally {
   if (inStream != null) {
    try {
     inStream.close();
    }catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return success;
 }
 /*** 
  *  The download file  
  * @param remoteFileName  Name of file to download  
  * @param localDires  Download to the local path  
  * @param remoteDownLoadPath remoteFileName The path  
  * */ 
 public boolean downloadFile(String remoteFileName, String localDires, 
   String remoteDownLoadPath) {
  String strFilePath = localDires + remoteFileName;
  BufferedOutputStream outStream = null;
  boolean success = false;
  try {
   this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
   outStream = new BufferedOutputStream(new FileOutputStream( 
     strFilePath));
   logger.info(remoteFileName + " Start the download ....");
   success = this.ftpClient.retrieveFile(remoteFileName, outStream);
   if (success == true) {
    logger.info(remoteFileName + " Successfully downloaded " + strFilePath);
    return success;
   }
  }catch (Exception e) {
   e.printStackTrace();
   logger.error(remoteFileName + " Download failed ");
  }finally {
   if (null != outStream) {
    try {
     outStream.flush();
     outStream.close();
    }catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  if (success == false) {
   logger.error(remoteFileName + " Download failed !!!");
  }
  return success;
 }
 /*** 
  * @ Upload folder  
  * @param localDirectory 
  *    Local folder  
  * @param remoteDirectoryPath 
  *   Ftp  Server path   In the directory "/" The end of the  
  * */ 
 public boolean uploadDirectory(String localDirectory, 
   String remoteDirectoryPath) {
  File src = new File(localDirectory);
  try {
   remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
   boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
   System.out.println("localDirectory : " + localDirectory);
   System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
   System.out.println("src.getName() : " + src.getName());
   System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
   System.out.println("makeDirFlag : " + makeDirFlag);
   // ftpClient.listDirectories();
  }catch (IOException e) {
   e.printStackTrace();
   logger.info(remoteDirectoryPath + " Directory creation failed ");
  }
  File[] allFile = src.listFiles();
  for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
   if (!allFile[currentFile].isDirectory()) {
    String srcName = allFile[currentFile].getPath().toString();
    uploadFile(new File(srcName), remoteDirectoryPath);
   }
  }
  for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
   if (allFile[currentFile].isDirectory()) {
    //  recursive  
    uploadDirectory(allFile[currentFile].getPath().toString(), 
      remoteDirectoryPath);
   }
  }
  return true;
 }
 /*** 
  * @ Download folder  
  * @param localDirectoryPath Local address  
  * @param remoteDirectory  Remote folder  
  * */ 
 public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
  try {
   String fileName = new File(remoteDirectory).getName();
   localDirectoryPath = localDirectoryPath + fileName + "//";
   new File(localDirectoryPath).mkdirs();
   FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
   for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
    if (!allFile[currentFile].isDirectory()) {
     downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
    }
   }
   for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
    if (allFile[currentFile].isDirectory()) {
     String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
     downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
    }
   }
  }catch (IOException e) {
   e.printStackTrace();
   logger.info(" Download folder failed ");
   return false;
  }
  return true;
 }
 // FtpClient the Set  and  Get  function  
 public FTPClient getFtpClient() {
  return ftpClient;
 }
 public void setFtpClient(FTPClient ftpClient) {
  this.ftpClient = ftpClient;
 }
 public static void main(String[] args) throws IOException {
  FTPTest_04 ftp=new FTPTest_04("10.0.0.102",21,"admin","123456");
  ftp.ftpLogin();
  System.out.println("1");
  // Upload folder  
  boolean uploadFlag = ftp.uploadDirectory("D:\\test02", "/"); // If it is admin/ So all the files are transferred, if only / So it's passing folders 
  System.out.println("uploadFlag : " + uploadFlag);
  // Download folder  
  ftp.downLoadDirectory("d:\\tm", "/");
  ftp.ftpLogOut();
 }
}

Related articles: