List files and directories recursively on a FTP server
- Details
- Written by Nam Ha Minh
- Last Updated on 25 August 2018   |   Print Email
- Retrieve a list of files using listFiles() method.
- 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.
- If the file is actually a directory:
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.
- 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.
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:- 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:
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.
Comments
for (int i = 1; i
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
now i m working for implement it on intranetwork. so how can i pass multiple ip as host?
Did you declare RemoteException in your remote methods?