Open In App

How to get a list of files from the FTPserver?

As know FTP is a reliable protocol used for transferring files over the Internet. Though it is not a secure protocol, and all the data is transmitted in clear text. But it is reliable enough protocol and send the data from a sender to receiver over Internet.
The code talks about getting the names of the all the files you wish to read from on a FTP server using the following process:




// Java code to illustrate
// How to get a list of files from the FTPserver
import java.io.IOException;
  
import org.apache.commons.net.ftp.FTPClient;
  
public class MyFTPClass {
    public static void main(String args[])
    {
  
        // Create an instance of FTPClient
        FTPClient ftp = new FTPClient();
        try {
            // Establish a connection with the FTP URL
            ftp.connect("ftp.test.com");
            // Enter user details : user name and password
            boolean isSuccess = ftp.login("user", "password");
  
            if (isSuccess) {
                // Fetch the list of names of the files. In case of no files an
                // empty array is returned
                String[] filesFTP = ftp.listNames();
                int count = 1;
                // Iterate on the returned list to obtain name of each file
                for (String file : filesFTP) {
                    System.out.println("File " + count + " :" + file);
                    count++;
                }
            }
  
            ftp.logout();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                ftp.disconnect();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


Article Tags :