FTPClient

org.apache.commons.net.ftp.ftpclient Example

In this example we are going to elaborate the use of the FTPClient class in the package: org.apache.commons.net.ftp, as the package name says, it is a member of the Apache Commons, and deals with the FTP. As like other classes of the Apache Commons This class also provides us with some really helpful methods. The methods of this class as other classes of Apache Commons Net FTP are wrappers for FTP manipulation, so the code which implemented those methods becomes significantly smaller, cleaner and understandable comparing to other programs where those functionalities are written manually.

1. A Closer Look to the org.apache.commons.net.ftp Package

The Apache Commons Net FTP package provides utilities for dealing with FTP operations (Client/Server). The package shows “FTP and FTPS support classes” in its description. It is a very usefull package when writting codes that will deal with FTP. It contains many usefull class and interface, out of which we will be using org.apache.commons.net.ftp.FTP, org.apache.commons.net.ftp.FTPFile, org.apache.commons.net.ftp.FTPClient and org.apache.commons.net.ftp.FTPReply in this post.

2. The FTPClient class overview & Methods.

FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface. As with all classes derived from SocketClient, you must first connect to the server with connect(), and then login with login() before doing anything, and finally disconnect()after you’re completely finished interacting with the server. Then you need to check the FTP reply code to see if the connection was successful. There are many methods found inside the FTPClient class, out of which we will discuss some most important methods.

2.1 FTPClient Methods Summary

  • public FTPClient() : Default FTPClient constructor. Creates a new FTPClient instance with the data connection mode set to ACTIVE_LOCAL_DATA_CONNECTION_MODE , the file type set to FTP.ASCII_FILE_TYPE , the file format set toFTP.NON_PRINT_TEXT_FORMAT , the file structure set to FTP.FILE_STRUCTURE , and the transfer mode set to FTP.STREAM_TRANSFER_MODE .
  • public void connect(String hostname) : Inherited from SocketClient. Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port. Before returning, _connectAction_() is called to perform connection initialization actions.
  • public boolean login(String username,String password) throws IOException : Login to the FTP server using the provided username and password.
  • public void enterLocalPassiveMode() : Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE . Use this method only for data transfers between the client and server. This method causes a PASV (or EPSV) command to be issued to the server before the opening of every data connection, telling the server to open a data port to which the client will connect to conduct data transfers. The FTPClient will stay in PASSIVE_LOCAL_DATA_CONNECTION_MODE until the mode is changed by calling some other method such as enterLocalActiveMode().
  • public FTPFile[] listFiles() throws IOException : Using the default system autodetect mechanism, obtain a list of file information for the current working directory.This information is obtained through the LIST command. The contents of the returned array is determined by the FTPFileEntryParser used.N.B. the LIST command does not generally return very precise timestamps. For recent files, the response usually contains hours and minutes (not seconds). For older files, the output may only contain a date.
  • public boolean changeWorkingDirectory(String pathName) throws IOException : Change the current working directory of the FTP session. pathName – The new current working directory.
  • public boolean storeFile(String remote,InputStream local) throws IOException : Stores a file on the server using the given name and taking input from the given InputStream. This method does NOT close the given InputStream. If the current file type is ASCII, line separators in the file are transparently converted to the NETASCII format (i.e., you should not attempt to create a special InputStream to do this). remote – The name to give the remote file, local – The local InputStream from which to read the file.
  • public boolean makeDirectory(String pathname) throws IOException : Creates a new subdirectory on the FTP server in the current directory (if a relative pathname is given) or where specified (if an absolute pathname is given). pathname – The pathname of the directory to create.
  • public InputStream retrieveFileStream(String remote) throws IOException : Returns an InputStream from which a named file from the server can be read. If the current file type is ASCII, the returned InputStream will convert line separators in the file to the local representation. You must close the InputStream when you finish reading from it. The InputStream itself will take care of closing the parent data connection socket upon being closed.To finalize the file transfer you must call completePendingCommand and check its return value to verify success. If this is not done, subsequent commands may behave unexpectedly.
    remote – The name of the remote file.
  • public boolean completePendingCommand() throws IOException : There are a few FTPClient methods that do not complete the entire sequence of FTP commands to complete a transaction. These commands require some action by the programmer after the reception of a positive intermediate command. After the programmer’s code completes its actions, it must call this method to receive the completion reply from the server and verify the success of the entire transaction.
  • public boolean deleteFile(String pathname) throws IOException : Deletes a file on the FTP server. pathname – The pathname of the file to be deleted.
  • public boolean logout() throws IOException : Logout of the FTP server by sending the QUIT command.
  • public void disconnect() : Inherited from SocketClient. Disconnects the socket connection. You should call this method after you’ve finished using the class instance and also before you call connect() again.

3. Setup FTP Server

For this project I’ve used localhost – xampp apache server and FileZilla as the FTP Server. below is the guideline on how to setup the FTP Server.

  • Step – 1 : Open XAMPP Control Panel and start FileZilla, then Click on Admin.
     
    XAMPP Control Panel
    XAMPP Control Panel
  • Step – 2 : Connect to the local server. FileZilla Server Admin Panel will open up.
     
    FTP Connect
    FTP Connect
  • Step – 3 : Click on “Edit” -> “Users”
     
    FileZilla Server Admin
    FileZilla Server Admin
  • Step – 4 : In the Users area Click on “Add”, Enter User Name, Click on Ok.
     
    Add User Name
    Add User Name
  • Step – 5 : Enter Desired Password, Click on “Shared Folders” and browse to the project folder to share.
     
    Password
    Password

     
    FTP Share Folder
    FTP Share Folder
  • Step – 6: Click on Ok.

4. FTPClient Example

The Complete code:

FTPClientExample.java

package com.webege.rivu.jcg.org.apache.commons.net.ftp.ftpclient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPClientExample {
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try{
		
			FTPClient ftp = new FTPClient();
			
			String serverAddress="127.0.0.1",userId="user",password="password";
			
			//try to connect
	        ftp.connect(serverAddress);
	        
	        //login to server
	        if(!ftp.login(userId, password))
	        {
	            ftp.logout();
	            System.out.println("Login Error");
	        }
	        
	        int reply = ftp.getReplyCode();
	        //FTPReply stores a set of constants for FTP reply codes. 
	        if (!FTPReply.isPositiveCompletion(reply))
	        {
	            ftp.disconnect();
	            System.out.println("Connection Error");
	        }
	
	        //enter passive mode
	        ftp.enterLocalPassiveMode();
	        //get system name
	        System.out.println("Remote system is " + ftp.getSystemType());
	        //get current directory
	        System.out.println("Current directory is " + ftp.printWorkingDirectory());
	        
            //get list of filenames
	        FTPFile[] ftpFiles = ftp.listFiles();  
	        
	       
	        if (ftpFiles != null && ftpFiles.length > 0) {
	            //loop thru files
	            for (FTPFile file : ftpFiles) {
	                if (file.isFile()) {
	                	System.out.println("File is " + file.getName());
	                } else if (file.isDirectory()){
	                	System.out.println("Directory is " + file.getName());
	                }
	                
	            }
	        }
	        
	        
	        //change current directory
	        ftp.changeWorkingDirectory("FTPClientExample");
            System.out.println("Current directory is " + ftp.printWorkingDirectory());
	        
            String localFileFullName="D:\\JCGExample\\myfile.txt";
            
            File localFile=new File(localFileFullName);
            
            FileInputStream input = new FileInputStream(localFile);
            
            if(ftp.storeFile( localFile.getName(), input)){
            	System.out.println("File Upload Successfull");
            }
            
            input.close();
            
            //Create Sub-Directory
            if(ftp.makeDirectory("subdir1")){
            	System.out.println("Directory Creation Successfull");
            } else {
            	System.out.println("Directory Creation Failed");
            }
            
            //get list of filenames
	        ftpFiles = ftp.listFiles();  
	        
	       
	        if (ftpFiles != null && ftpFiles.length > 0) {
	            //loop thru files
	        	for (FTPFile file : ftpFiles) {
	                if (file.isFile()) {
	                	System.out.println("File is " + file.getName());
	                } else if (file.isDirectory()){
	                	System.out.println("Directory is " + file.getName());
	                }
	                
	               
	               
	                
	                
	               
	            }
	        }
	        
	        System.out.println("Uploaded File Content\n[");
	        //Getting the File in an InputStream
	        
	        InputStream remoteInput=ftp.retrieveFileStream(localFile.getName());
	        BufferedReader in = new BufferedReader(new InputStreamReader(remoteInput));
	        String line = null;
	        while((line = in.readLine()) != null) {
	          System.out.println(line);
	        }
	        
	        System.out.println("]");
	        
	        remoteInput.close();
	        
	        //call completePendingCommand and check its return value to verify success. If this is not done, subsequent commands may behave unexpectedly
	        if(!ftp.completePendingCommand()){
	        	System.out.println("Completing Pending Commands Not Successfull");
	        }
	       
	        //Download All Files to Local Directory and Delete from Server
	        
	        ftpFiles = ftp.listFiles();  
	        
	        String localDirectory="D:\\JCGExample\\localDirectory";
	           
            if (ftpFiles != null && ftpFiles.length > 0) {
                //loop thru files
                for (FTPFile file : ftpFiles) {
                    if (!file.isFile()) {
                        continue;
                    }
                    System.out.println("File is " + file.getName()+" getting Downloaded");
                   
                   
                    //get output stream
                    OutputStream output;
                    
                    File outfile=new File(localDirectory + "/" + file.getName());
                    outfile.createNewFile();
                    
					output = new FileOutputStream(outfile);
                    //get the file from the remote system
                    ftp.retrieveFile(file.getName(), output);
                    //close output stream
                    output.close();
                   
                    //delete the file
                    ftp.deleteFile(file.getName());
                    
                    System.out.println("File " + outfile.getName()+" Download Successfull");
                   
                }
            }
	        
	        ftp.logout();
	        ftp.disconnect();
	    }
	    catch (IOException ex)
	    {
	        ex.printStackTrace();
	        
	    }
        

	}

}

Output:

Remote system is UNIX emulated by FileZilla
Current directory is /
File is applications.html
Directory is associative_array
File is bitnami.css
Directory is dashboard
File is favicon.ico
Directory is FTPClientExample
Directory is img
File is index.php
Directory is webalizer
Directory is xampp
Current directory is /FTPClientExample
File Upload Successfull
Directory Creation Successfull
File is myfile.txt
Directory is subdir1
Uploaded File Content
[
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eros quam, sodales quis diam ac, tempus suscipit sem. Aenean nisi dolor, suscipit et diam id, cursus efficitur lectus. Curabitur aliquam pellentesque pulvinar. Donec sed nulla sapien. Sed faucibus magna libero, ut vehicula nulla egestas ut. Nullam egestas lobortis metus, in volutpat felis pharetra ut. Cras auctor arcu lectus, eget dictum velit egestas eu. Integer sed malesuada arcu. Nullam sagittis tincidunt accumsan. Vestibulum porta cursus nibh, vitae sodales nulla blandit quis. Proin et ornare est, eget efficitur magna.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam malesuada dignissim diam, vel feugiat massa consectetur eu. Sed viverra quam eget elementum vulputate. Nam et metus sit amet lacus pulvinar pellentesque. Quisque lobortis dolor eget felis gravida hendrerit. Praesent porta, neque vel tincidunt pharetra, risus est sollicitudin arcu, nec feugiat augue quam a nibh. Etiam volutpat, erat eu posuere auctor, lacus urna vulputate justo, blandit luctus nunc risus mollis lorem.
]
File is myfile.txt getting Downloaded
File myfile.txt Download Successfull

4.1 Explanation

In the above code I’ve tried to implement some most important aspects of FTP,

  • Connecting to FTP
  • Login to FTP with userid and password
  • get File/Directory List from FTP
  • Change Directory
  • Upload file
  • Create Directory
  • read file content from FTP
  • Download files
  • delete file from FTP server
  • Log out and disconnect from server

In this section I’ll describe all of those one after another. First of all I’ve created an object of the FTPClient, then connected it to the server and logged in (For your information, I’ve used localhost – xampp apache server, FileZilla – as I already mentioned with userid as "user" and password as "password"). While logging in to the server I’ve checked the status and reply to check if login was successful, otherwise disconnected from the server. After successfull login, I switched to passive mode with the help of ftp.enterLocalPassiveMode(); function. After that I’ve listed all the contents of the current directory with the help of following lines of code:

//get list of filenames
FTPFile[] ftpFiles = ftp.listFiles();  

if (ftpFiles != null && ftpFiles.length > 0) {
   //loop thru files
   for (FTPFile file : ftpFiles) {
	  if (file.isFile()) {
	      System.out.println("File is " + file.getName());
	  } else if (file.isDirectory()){
	      System.out.println("Directory is " + file.getName());
	  }
	                
   }
}

Then I got into a sub-directory named “FTPClientExample”, printed that, uploaded a local file that is in the location “D:\JCGExample\myfile.txt” to the server with the following lines of code:

String localFileFullName="D:\\JCGExample\\myfile.txt";
            
File localFile=new File(localFileFullName);
            
FileInputStream input = new FileInputStream(localFile);
            
if(ftp.storeFile( localFile.getName(), input)){
     System.out.println("File Upload Successfull");
}
            
input.close();

For creating a subdirectory I’ve used the makeDirectory(String pathname) method (You can see, line no 87 through 91). Again printed all the containings of current directory. After that I’ve printed the contents of the newly uploaded files (line 114 through 124). Then from line 139 through 166 printed all the containings of current directory, and finally logged out of server and disconnected (line no. 168,169).

In this approach I’ve tried to implement the most of the important methods of the FTPClient class.

5. Download The Source Code

This was an Example for FTPClient in Apache Commons Net FTP.

Download
You can download the full source code of this example here: FTPClient Example

Rivu Chakraborty

Rivu Chakraborty is a Google Certified Android Developer, Sr. Tech Member of Institute of Engineers (India), he also have certifications on Scrum. He is also an author of multiple books on Kotlin, Reactive Programming, Functional Programming and Android Development, published by renowned publication houses. Having total 5+ years of experience he is presently working as a Sr. Software Engineer (Android) at Indus Net Technologies Pvt. Ltd. Rivu Chakraborty considers himself a Kotlin and Android enthusiast and a Kotlin evangelist. He has been using Kotlin since December 2015, so he has around 2 years' experience in Kotlin. As part of his mission to expand the use and knowledge of the Kotlin Language as much as possible, he created the KotlinKolkata User Group, one of the most active Kotlin user groups throughout the world and he is a Founder Organizer of KotlinKolkata. He is also an active member of GDG Kolkata and gives talks at GDG Kolkata Meetups.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button