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

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
//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:

01
02
03
04
05
06
07
08
09
10
11
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
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button