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: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();
}
}
}
}
You can download the sample program source code in the attachment section at the end of this article.NOTE:a
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.