FTP Server : List Files and Directories
In this tutorial we will discuss how to list files and directories on FTP server using java.
List Files and Directories :
By using FTP Server we can transfer files from one computer to another computer through network and internet. You must be valid user for using FTP server. Before applying any operation on FTP server first we need to connect to the server by using connect(hostname) method of FTPClient class next input valid user name and password to login by calling method login("username","password");
client.connect("localhost");
result = client.login("admin", "admin");
listFiles() : This method of FTPClient is used to list all files and directories of the current FTP server directory. This method returns array of FTPFile object which list the files and directories.
FTPFile[] files = client.listFiles();
FTPFile class supply many methods which is used to handle file and directories like getName(), getSize(), isDirectory(), isFile(), getTimestamp().
Example : In this example we are listing all the files and directories of FTP server and displaying the same.
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 FTPListFiles { public static void main(String[] args) throws IOException { FTPClient client = new FTPClient(); boolean result; try { client.connect("localhost"); result = client.login("admin", "admin"); client.changeWorkingDirectory("c:\ftp"); if (result == true) { System.out.println("User successfully logged in."); } else { System.out.println("Login failed!"); return; } FTPFile[] files = client.listFiles(); System.out.println("Files and directories on Ftp Server directory : "); for (FTPFile file : files) { System.out.println(file.getName()); } } catch (FTPConnectionClosedException e) { System.out.println(e); } finally { try { client.disconnect(); } catch (FTPConnectionClosedException e) { System.out.println(e); } } } }
Output :
User successfully logged in. Files and directories on Ftp Server directory : . .. ApacheServer.shtml filetest FtpConnect.shtml FtpTopic.txt FtpTutorial.txt