In this section you will learn how to list all the directories on FTP server using java.
List all Directories :
FTPClient class provides method listDirectories() to list the all directory names of the ftp server. There is another way to list the directory. For that first list all files and directory by using method listFiles() and then check by using FTPFile method isDirectory().
FTPFile[] listDirectories() : This method returns the list of directories on the current directory of ftp server. Return type of this method is array of FTPFile. This method throws IOException.
Example : In this example we are using listDirectories() of FTPClient class to list all the directories of FTP server.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
class FtpListDirectory {
public static void main(String[] args) throws IOException {
FTPClient client = new FTPClient();
boolean result;
try {
client.connect("localhost");
result = client.login("admin", "admin");
if (result == true) {
System.out.println("User successfully logged in.");
} else {
System.out.println("Login failed!");
return;
}
FTPFile[] files = client.listDirectories();
System.out.println("List of Directory on Ftp Server : ");
for (FTPFile file : files) {
if (file.equals('.')) {
System.out.println(" dfg");
} else {
System.out.println("Directory name : " + file.getName());
}
}
} catch (FTPConnectionClosedException e) {
System.out.println(e);
} finally {
try {
client.disconnect();
} catch (FTPConnectionClosedException e) {
System.out.println(e);
}
}
}
}
Output :
List of Directory on Ftp Server : Directory name : . Directory name : .. Directory name : filetest Directory name : upload123
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: List all directory on FTP Server
Post your Comment