Home » Core Java » apache » commons » net » Download file from FTP Server

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Download file from FTP Server

This is an example of how to download a File from an FTP Server, using the org.apache.commons.net.ftp.FTPClient Class, that encapsulates all the functionality necessary to store and retrieve files from an FTP server. Downloading a File from an FTP Server implies that you should:

  • Create a new FTPClient.
  • Use connect() API method to open a connection to the FTP Server.
  • Use the login(String username, String password) API method to login to the FTP server using the provided username and password. It returns true if it is successfully completed and false otherwise.
  • Create a FileOutputStream to write to the file with the specified name.
  • Use retrieveFile(String remote, OutputStream local) method to retrieve a named file from the server and write it to the given outputStream.
  • Use logout() method to logout of the FTP server by sending the QUIT command and disconnect() method to close the connection to the FTP server. Don’t forget to also close the outputStream.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.FileOutputStream;
 
public class FtpFileDownload {
	
    public static void main(String[] args) {
    	

  FTPClient client = new FTPClient();

  FileOutputStream fos = null;
 

  try {


client.connect("ftp.javacodegeeks.com");


client.login("username", "password");
 


// Create an OutputStream for the file


String filename = "test.txt";


fos = new FileOutputStream(filename);
 


// Fetch file from server 


client.retrieveFile("/" + filename, fos);

  } catch (IOException e) {


e.printStackTrace();

  } finally {


try {


    if (fos != null) {



  fos.close();


    }


    client.disconnect();


} catch (IOException e) {


    e.printStackTrace();


}

  }
 
    }
}

 
This was an example of how to download a File from an FTP Server in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments