The article List files and directories on a FTP server describes the Apache Commons NET’s FTP API for listing files and directories of the current working directory or a specific one on a FTP server. All the methods listFiles() and listDirectories() list only files and directories which are directly under the directory being listed, not all sub files and sub directories nested in the directory’s hierarchical structure.

The algorithm to list all nested sub files and directories is as follows:

  1. Retrieve a list of files using listFiles() method.
  2. For each file in the list:
    • If the file is actually a directory:
      • Print out directory name.
      • Repeat step 1 and step 2 with the current directory.
    • If the file is actually a file:
      • Print out file name.
    • Continue until with the next file, until the last file is reached.
The following method implements the algorithm described above:

static void listDirectory(FTPClient ftpClient, String parentDir,
        String currentDir, int level) throws IOException {
    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }
    FTPFile[] subFiles = ftpClient.listFiles(dirToList);
    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".")
                    || currentFileName.equals("..")) {
                // skip parent directory and directory itself
                continue;
            }
            for (int i = 0; i < level; i++) {
                System.out.print("\t");
            }
            if (aFile.isDirectory()) {
                System.out.println("[" + currentFileName + "]");
                listDirectory(ftpClient, dirToList, currentFileName, level + 1);
            } else {
                System.out.println(currentFileName);
            }
        }
    }
}
 

The method has 4 parameters:

    •           ftpClient: a FTPClient object on whose listFiles() method is invoked.
    •           parentDir: Name of the parent directory.
    •           currentDir: Name of the current directory being listed.
    •           level: a number is used to indent the output looks like a hierarchical structure.
There are some notes about the implementation of the method above:

    •           We need to construct full path of the directory by concatenating the parentDir and the currentDir (line 4 to 6).
    •           Because the listFiles() method always returns the parent directory (denote by two dots: ..) and the current directory (denoted by one dot: .), so we need to check and skip them (line 11 to 15).
    •           Each indent level in the output represented by a tab character (\t) (line 17).
    •           The line 21 calls the method itself which is called recursion algorithm.
 

And following is a sample program that connects, logins to lists a particular directory on a FTP server. After that it logs out and disconnects from the server.

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPListRecursiveDemo {
    static void listDirectory(FTPClient ftpClient, String parentDir,
            String currentDir, int level) throws IOException {
        String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }
        FTPFile[] subFiles = ftpClient.listFiles(dirToList);
        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".")
                        || currentFileName.equals("..")) {
                    // skip parent directory and directory itself
                    continue;
                }
                for (int i = 0; i < level; i++) {
                    System.out.print("\t");
                }
                if (aFile.isDirectory()) {
                    System.out.println("[" + currentFileName + "]");
                    listDirectory(ftpClient, dirToList, currentFileName, level + 1);
                } else {
                    System.out.println(currentFileName);
                }
            }
        }
    }
    public static void main(String[] args) {
        String server = "www.myserver.com";
        int port = 21;
        String user = "username";
        String pass = "password";
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Connect failed");
                return;
            }
            boolean success = ftpClient.login(user, pass);
            if (!success) {
                System.out.println("Could not login to the server");
                return;
            }
            String dirToList = "/public_html/images/articles";
            listDirectory(ftpClient, dirToList, "", 0);
        } catch (IOException ex) {
            System.out.println("Oops! Something wrong happened");
            ex.printStackTrace();
        } finally {
            // logs out and disconnects from server
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
 



When running, the program’s output looks like the following screenshot:

list ftp recursive output

 

You can download the sample program source code in the attachment section at the end of this article.

NOTE:

    •           The code is this article is only working with Apache Commons NET’s FTP API. See the article How to start FTP programming with Java for how to get the library.
    •           You may need to turn off firewall on your computer to run the sample program.

a


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (FTPListRecursiveDemo.java)FTPListRecursiveDemo.java[sample program]2 kB

Add comment

   


Comments 

#10Victor2015-05-07 11:06
Congratulations Magnific Code,
Quote
#9kinjal2015-03-25 06:39
Quoting kinjal:
I am trying to search file in network using RMI..bt still geting error here is the code for this.

public class client {

public static void main(String[] args) throws NotBoundException {
try {
String fileName1;
System.out.print("Please Enter file Name-\t");
BufferedReader fileNameReader = new BufferedReader(
new InputStreamReader(System.in));
fileName1 = fileNameReader.readLine();
InetAddress localhost = InetAddress.getLocalHost(); // this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 1; i

for (int i = 1; i
Quote
#8kinjal2015-03-25 06:37
I am trying to search file in network using RMI..bt still geting error here is the code for this.

public class client {

public static void main(String[] args) throws NotBoundException {
try {
String fileName1;
System.out.print("Please Enter file Name-\t");
BufferedReader fileNameReader = new BufferedReader(
new InputStreamReader(System.in));
fileName1 = fileNameReader.readLine();
InetAddress localhost = InetAddress.getLocalHost(); // this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 1; i
Quote
#7kinjal2015-03-16 02:57
yeh..i solved it.thanks a lot.
now i m working for implement it on intranetwork. so how can i pass multiple ip as host?
Quote
#6Nam2015-03-15 10:12
Hi kinjal,

Did you declare RemoteException in your remote methods?
Quote