Upload and Download file from FTP Server using Java FTP Client
Recently within my project, I stumbled upon a requirement where I had to test one of the application’s functionality to upload/download the file via FTP Server. It was pretty much straight forward to do the same manually by using any of the FTP Client for example Filezilla but equally difficult to automate the process. Thus, after researching a bit, I found Java FTP Client which makes it a task of just method calls.
Thus, though this blog, I would make you acquainted with Java FTP Client API, its basic methods, its usefulness and the code sample that can be readily used by the readers within their project. Therefore, today we would “Upload and Download file from FTP Server using Java FTP Client”.
[the_ad_placement id=”incontent”]
Before imitating with the code, there is one library that needs to be downloaded and configured within the project’s build path to be able to access the methods of Java FTP Client. Refer the following steps:
- Download the zipped “Apache Commons Net” folder from here.
- Extract the folder at any desired location on to your file system.
- Configure the project and add the “commons-net-3.3.jar” file available within the downloaded folder as external library.
Let us now motion towards the sample code for the following functionalities:
- Upload a file on the FTP Server
- Download a file from the FTP Server
- List the file in a particular directory located at the FTP Server and verify the presence of a particular file.
Sample Code
[the_ad_placement id=”incontent”]
Before developing the code for the aforementioned functionalities, we would create a java class “FTPFunctions.java” under which we would define all the functionalities. Check out the code below:
Paste your text import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import static org.junit.Assert.assertTrue;
public class FTPFunctions {
// Creating FTP Client instance
FTPClient ftp = null;
// Constructor to connect to the FTP Server
public FTPFunctions(String host, int port, String username, String password) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host,port);
System.out.println("FTP URL is:"+ftp.getDefaultPort());
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
// Method to upload the File on the FTP Server
public void uploadFTPFile(String localFileFullName, String fileName, String hostDir)
throws Exception
{
try {
InputStream input = new FileInputStream(new File(localFileFullName));
this.ftp.storeFile(hostDir + fileName, input);
}
catch(Exception e){
}
}
// Download the FTP File from the FTP Server
public void downloadFTPFile(String source, String destination) {
try (FileOutputStream fos = new FileOutputStream(destination)) {
this.ftp.retrieveFile(source, fos);
} catch (IOException e) {
e.printStackTrace();
}
}
// list the files in a specified directory on the FTP
public boolean listFTPFiles(String directory, String fileName) throws IOException {
// lists files and directories in the current working directory
boolean verificationFilename = false;
FTPFile[] files = ftp.listFiles(directory);
for (FTPFile file : files) {
String details = file.getName();
System.out.println(details);
if(details.equals(fileName))
{
System.out.println("Correct Filename");
verificationFilename=details.equals(fileName);
assertTrue("Verification Failed: The filename is not updated at the CDN end.",details.equals(fileName));
}
}
return verificationFilename;
}
// Disconnect the connection to FTP
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
}
}
}
// Main method to invoke the above methods
public static void main(String[] args) {
try {
FTPFunctions ftpobj = new FTPFunctions("abodeqa4.noid.blog.int", 2121, "shruti", "password");
ftpobj.uploadFTPFile("C:\\Users\\shruti\\Shruti.txt", "Shruti.txt", "/");
ftpobj.downloadFTPFile("Shruti.txt", "/users/shruti/Shruti.txt");
System.out.println("FTP File downloaded successfully");
boolean result = ftpobj.listFTPFiles("/users/shruti", "shruti.txt");
System.out.println(result);
ftpobj.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The code above is self explanatory. Just to brief a bit, refer the following points:
- The constructor is created to connect with the FTP Server using host name and port number.
- The upload method is created to upload the file to a particular directory on the FTP Server.
- The download methods are created to download the file from the FTP Server to the local machine.
- The list method is created to check if the particular file is present inside the specified directory on the FTP Server.
I hope your search ends here and the content is relevant with respect to your needs. Please add if you have any suggestions or advise on this blog.
Great work!
Thank you Anurag.
Hi Shruti,
Nice article, finally Even I got such requirement and I tried above code but I am facing some proxy issue in my organisation. I tried proxy class and proxy class in Selenium as well but did not find a way to overcome with it. Can you please guide me in this so that I can apply the same in my code on Monday
@mukesh. Did you find any solution for this?
Even i am getting this error “Connection refused: connect”
what is the problem of downloading files ..everytime i do it will be download a corrupted files… please give me a tips to fix it tnx…
Thanks so much for sharing this with us Shruti. It is very helpful. I have a question. What if I am using public/private key to connect to the server instead of password? What should I do? Any help would be definitely appreciated.
Nicely written. It helped. Thanks
Hi Shruti,
Nice explanation , it will help for my project .
I need your help for my project,
do you know how to convert FTPFile format into File format(IO package)?
Ex:
FTPFile[] ftpFiles = fClient.listFiles();
for(FTPFile ftpFile : allFiles) {
// here ftpFile, I need fileFtp convert into File(IO package)
}
Great article. I’m gonna write automated test checks that application upload file on ftp. I think it is what I was looking for. And maybe do you know some library for mock ftp server ?