Sample code for 30+ languages & platforms
Java

Get FTP Directory Listing Information

See more FTP Examples

_LANGUAGE_ example showing how to get information about files and subdirectories in the current remote FTP directory.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ftp2;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Ftp2 ftp = new Ftp2();

        ftp.setHostname("ftp.example.com");
        ftp.setUsername("login");
        ftp.setPassword("password");

        // Connect and login to the FTP server.
        try {
            ftp.connect();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The ListPattern property is our directory listing filter.
        // The default value is "*", which includes everything.
        System.out.println(ftp.getListPattern());

        // To get file and sub-directory information, simply
        // loop from 0 to ftp.GetDirCount() - 1
        int n = ftp.getDirCount();
        if (n < 0) {
            System.out.println(ftp.getLastErrorText());
            return;
        }

        if (n > 0) {
            for (int i = 0; i < n; i++) {
                // Display the filename
                System.out.println(ftp.getFilename(i));

                // Display the file size (in bytes)
                System.out.println(ftp.getSize(i));

                // Is this a sub-directory?
                if (ftp.getIsDirectory(i)) {
                    System.out.println(".. this is a sub-directory");
                }

                System.out.println("--");
            }
        }

        System.out.println("-----------------------------------");

        // Only files and directories
        // matching the ListPattern are returned.
        ftp.setListPattern("*.asp");
        n = ftp.getDirCount();
        if (n < 0) {
            System.out.println(ftp.getLastErrorText());
            return;
        }

        if (n > 0) {
            for (int i = 0; i < n; i++) {
                // Display the filename
                System.out.println(ftp.getFilename(i));

                // Display the file size (in bytes)
                System.out.println(ftp.getSize(i));

                System.out.println("--");
            }
        }

        ftp.disconnect();
    }
}