Sample code for 30+ languages & platforms
Java

FTP Iterate over Files in Directory Matching ListPattern

See more RSA Examples

Uses the ListPattern property to iterate over the files in a directory matching the pattern.

Chilkat Java Downloads

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

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("my_login");
        ftp.setPassword("my_password");
        ftp.setPort(21);
        ftp.setAuthTls(true);

        try {
            ftp.connect();

            // Change to the "images" sub-directory located under our FTP account's home directory.
            ftp.changeRemoteDir("images");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        ftp.setListPattern("*.png");

        // Fetch the current remote directory contents by calling GetDirCount
        int n = ftp.getDirCount();
        if (n < 0) {
            System.out.println(ftp.getLastErrorText());
            return;
        }

        int i = 0;
        String filename = "";
        StringBuilder sbLocalPath = new StringBuilder();

        while (i < n) {
            filename = ftp.getFilename(i);
            System.out.println(filename);

            // Download this file.
            sbLocalPath.setString("qa_output/");
            sbLocalPath.append(filename);
            try {
                ftp.getFile(filename, sbLocalPath.getAsString());
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            i = i + 1;
        }
    }
}