Sample code for 30+ languages & platforms
Java

Get a Filename from an FTP Directory Listing

See more FTP Examples

Demonstrates the Chilkat Ftp2.GetFilename method, which returns the name of a cached directory-listing entry. The only argument is a zero-based index from 0 through GetDirCount - 1.

Background: The Chilkat FTP directory API is index-based and works from a single cached listing: the first GetDirCount call fetches the current directory's listing once, and every indexed accessor — name, size, type, permissions, timestamps — then reads from that cache without further server round trips. That makes iterating a directory efficient, but it also means the data reflects the moment the listing was fetched; call ClearDirCache to force a refresh after the remote directory changes.

Chilkat Java Downloads

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

public class ChilkatExample {

    public static void main(String[] args) {
        // Demonstrates the Ftp2.GetFilename method, which returns the name of a cached directory-listing
        // entry.  The only argument is a zero-based index from 0 through GetDirCount - 1.

        Ftp2 ftp = new Ftp2();

        ftp.setHostname("ftp.example.com");
        ftp.setUsername("myFtpLogin");

        // Normally you would not hard-code the password in source.  You should instead obtain it
        // from an interactive prompt, environment variable, or a secrets vault.
        ftp.setPassword("myPassword");

        try {
            ftp.connect();

            ftp.changeRemoteDir("public_html");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // GetDirCount retrieves the directory listing on the first call and returns the number of
        // entries.  A negative return indicates failure.
        int n = ftp.getDirCount();
        if (n < 0) {
            System.out.println(ftp.getLastErrorText());
            return;
        }

        for (int i = 0; i < n; i++) {
            String name = ftp.getFilename(i);
            System.out.println(name);
        }

        try {
            ftp.disconnect();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }
    }
}