Java
Chilkat2 Java
Download Multiple FTP Files by Wildcard (MGET)
See more FTP Examples
Demonstrates the Chilkat Ftp2.MGetFiles method, which downloads files in the current remote directory matching a pattern into a local directory. The first argument is the remote pattern and the second is the local directory. It returns the number of files downloaded, or -1 on failure.
Note: The local paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.
Background: This is FTP's
mget: fetch everything matching a wildcard in one call rather than looping yourself. It operates on the current remote directory — hence the ChangeRemoteDir first — and does not descend into subdirectories; use DownloadTree for recursive transfers. The count return lets you confirm how many matched, with -1 signaling an outright failure to check separately from a legitimate zero.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ftp2;
public class ChilkatExample {
public static void main(String[] args) {
// Demonstrates the Ftp2.MGetFiles method, which downloads files in the current remote directory
// matching a pattern into a local directory. The 1st argument is the remote pattern and the 2nd
// is the local directory. It returns the number of files downloaded, or -1 on failure.
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;
}
// Download all .html files from the current remote directory. Subdirectories are not traversed.
int numDownloaded = ftp.mGetFiles("*.html", "qa_output/site");
if (numDownloaded < 0) {
System.out.println(ftp.getLastErrorText());
return;
}
System.out.println("Downloaded " + numDownloaded + " files.");
try {
ftp.disconnect();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
}
}