net

Get list of files from FTP Server

In this example we shall show you how to get a list of files from an FTP Server. We are using the org.apache.commons.net.ftp.FTPClient Class that encapsulates all the functionality necessary to store and retrieve files from an FTP server. To get a list of files from an FTP Server one should perform the following steps:

  • Create a new FTPClient.
  • Use connect() API method to open a connection to the FTP Server.
  • Use the login(String username, String password) API method to login to the FTP server using the provided username and password.
  • Use listFiles() to get a list of file information for the current working directory.
  • For every FTPFile, check the file type and print result.
  • Use logout() method to logout of the FTP server by sending the QUIT command and disconnect() method to close the connection to the FTP server,

as described in the code snippet below.  

package com.javacodegeeks.snippets.core;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
 
public class getFTPfileList {
	
    public static void main(String[] args) {
    	
  FTPClient client = new FTPClient();
 
  try {

client.connect("ftp.javacodegeeks.com");

client.login("username", "password");
 
// Get the files stored on FTP Server and store them into an array of FTPFiles
FTPFile[] files = client.listFiles();

for (FTPFile ftpFile : files) {
	// Check the file type and print result

    if (ftpFile.getType() == FTPFile.FILE_TYPE) {

  System.out.println("File: " + ftpFile.getName() +

    "size-> " + FileUtils.byteCountToDisplaySize(

    ftpFile.getSize()));
    }
}

client.logout();

  } catch (IOException e) {

e.printStackTrace();

  } finally {

try {
    client.disconnect();

} catch (IOException e) {

    e.printStackTrace();

}

  }
    }
}

Output:

File: index.html size-> 1 KB
FTPFile: page1.html size-> 1 KB
FTPFile: page2.html size-> 1 KB

  
This was an example of how to get a list of files from an FTP Server in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button