How to Get a File Efficiently Using FTP in Java
- 1). Open a text editor by double-clicking on its desktop icon. Create a FTP command file using the editor; that file contains a list of commands for the FTP client to execute. Enter the following text into the file:
open server.company.com
userid
password
get remoteFile.doc
bye
Replace "server.company.com" with the host name of the FTP server, "userid" with the name of your FTP account, "password" with the FTP account's password, and "remoteFile.doc" with the name of the file you want to get from the FTP server. Save the FTP command file as "ftpCommands.txt", then exit the text editor. - 2). Include the following lines at the beginning of your Java program:
import "java.io.*";
import "java.util.*"; - 3). Include the following line in your Java code, anywhere after the Java code quoted in previous steps:
Runtime runtimeContext = Runtime.getRuntime();
This line retrieves (a reference to) the current runtime context where your Java program is running; the FTP client will run on the same context. - 4). Include the following lines in your Java code to call the FTP client, anywhere after the Java code quoted in previous steps:
String[] myCall = {
"ftp",
"-s:ftpCommands.txt"
};
newProcess = runtimeContext.exec(myCall);
newProcess.waitFor();
This code creates a string array containing the name of the external program and its arguments (in this case, the name of the FTP command file); then, method Runtime.exec() actually calls the FTP client. Method Runtime.waitFor() waits until the FTP client completes to continue running your Java program. At that point, the remote file will have been downloaded from the FTP server.
Source...